Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve innermost template type within the template itself

is it possible to retrieve the innermost type of stacked templates of the same type from within the template? I'd like to retrieve the double type in the following example:

template<typename T>
struct is_a : std::false_type {};

template<typename T>
struct A
{
    using type = std::conditional_t<
        is_a<T>::value,
        T::type, // if it's an A, go deeper
        T>;      // if not, we're done
};
template<typename T>
struct is_a<A<T>> : std::true_type {};

int main()
{
    A<A<A<A<A<double>>>>>::type d = 3.0;
    return 0;
}

It was motivated by this question. Also, I found this post, indicating that it may have something do to with typename or template keyword placing, but I couldn't get it to work myself.

like image 603
Thomas B. Avatar asked May 15 '18 07:05

Thomas B.


2 Answers

Unless I'm missing something I'd just partially specialize a template to make things easier

template<typename T>
struct A
{
    using type = T;
};

template<typename T>
struct A<A<T>>
{
    using type = typename A<T>::type;
};

int main()
{
    A<double>::type a = 5.0;
    A<A<double>>::type d = 3.0;
    A<A<A<double>>>::type c = 9.5;
    return 0;
}

Live sample

like image 161
Marco A. Avatar answered Oct 13 '22 18:10

Marco A.


The usual trick to do it with your original approach is to defer evaluation:

template<class T> struct type_identity { using type = T; };

template<typename T>
struct A
{
    using type = typename std::conditional_t<
        is_a<T>::value,
        T,
        type_identity<T>>::type;
};
like image 11
T.C. Avatar answered Oct 13 '22 17:10

T.C.