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.
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
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With