Tho*_* B. 26 c++ templates types
是否可以从模板中检索最内层类型的相同类型的堆叠模板?我想double
在以下示例中检索该类型:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是出于这个问题的动机.此外,我发现这篇文章,表明它可能有一些事情typename
或template
关键字放置,但我无法让它自己工作.
Mar*_* A. 34
除非我遗漏了一些东西,否则我只会部分专门化一个模板来简化操作
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;
}
Run Code Online (Sandbox Code Playgroud)
T.C*_*.C. 11
使用原始方法执行此操作的常用技巧是推迟评估:
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;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1000 次 |
最近记录: |