Search code examples
c++c++11c++14variadic-templatestemplate-meta-programming

variadic template struct, recursive type declaration, is it possible?


there!

There is any way to declare a type recursively? I was almost there but I got a compile error.

I'm designing a simple template to determine the optimal type for storing the result of operating mixed type stuff.

OP_T<> Use case example:

typename OP_T<char, float, int>::M var //var is actually a float

Code

template <typename ...T>
struct OP_T{};

template <typename T0, typename T1>
struct OP_T<T0, T1> {
    using M = typename x_traits<T0, T1>::MULT_T;
};

template <typename T0, typename ...Ts>
struct OP_T<T0, Ts...> {
    using M = typename OP_T<T0, Ts...>::M; // error: 'M' is not a member of 'OP_T' 
};

This is x_traits simplified

template<typename T>
struct x_traits_default {
    typedef T MULT_T;
};

template<typename T1, typename T2>
struct x_traits {};

template<typename T2>
struct x_traits<double, T2> : public x_traits_default<double> {};

template<typename T1>
struct x_traits<T1, double> : public x_traits_default<double> {};

Here you can find a more detailed use case example (but still simplified): https://godbolt.org/z/jbcahq


Solution

  • I guess you meant something like this:

    template <typename T0, typename... Ts>
    struct OP_T<T0, Ts...> {
        using M = typename OP_T<T0, typename OP_T<Ts...>::M>::M;
    };
    

    Now OP_T<T1, T2, ...>::M will be a type obtained from the pack T1, T2, ... by the application of the "reduction" binary metafunction x_traits<S, T>::MULT_T, similar in spirit to what std::accumulate with a custom binary operation does.