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

Viewed 156

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

2 Answers

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.

I suspect thatSince you need result type of some chained operation this could look like this (using C++17 fold expression):

template<typename ...Ts>
using mutiplication_result_t = decltype((std::declval<Ts>() * ...));

Same for C++11:

template<typename T1, typename ...Ts>
struct mutiplication_result
{ 
    using type = decltype(std::declval<T1>() * std::declval<typename mutiplication_result<Ts ...>::type>());
};

template<typename T>
struct mutiplication_result<T>
{ 
    using type = typename std::decay<T>::type;
};

template<typename ...Ts>
using mutiplication_result_t = typename mutiplication_result<Ts...>::type;

https://godbolt.org/z/qnx1Y8

Related