Search code examples
c++templatesc-preprocessorvariadic-templatestemplate-meta-programming

How to optimize variadic template specializations?


Suppose you have the following struct to concatenate two templated structs:

/// concat.hpp
template<typename...>
struct concat_struct;

// concat_specialization.hpp
template<std::size_t... m, std::size_t... n>
struct concat_struct<$CLASSNAME<m...>, $CLASSNAME<n...>>
{
    using type = $CLASSNAME<m..., n...>;
};

template<typename a, typename b>
using concat = typename concat_struct<a, b>::type;

I can now do

#include "concat.hpp"
#define $CLASSNAME MyClass
#include "concat_specialization.hpp"
#undefine $CLASSNAME
#define $CLASSNAME MyOtherClass
#include "concat_specialization.hpp"

As is, this could easily lead to conflicts, if I were to include "concat_specialization.hpp" again. What is the C++ way, to handle multiple specializations of variadic templates?


Solution

  • You don't need to explicitly write out a specialization for each $CLASSNAME. You can just add a template template parameter to the specialization, and this will get deduced automatically:

    template<template<std::size_t...> typename C, std::size_t... m, std::size_t... n>
    struct concat_struct<C<m...>, C<n...>>
    {
        using type = C<m..., n...>;
    };
    

    Here's a demo