我想创建一个类型特征,用于检测某个其他感兴趣类型中是否存在嵌套类模板。
例如,假设我想创建类型特征 has_foo
,它检测某个类型 T 中是否存在一个名为
:foo
的参数的嵌套模板
#include <cassert>
template<class T>
struct has_foo
{
// XXX what goes here?
};
struct with_foo
{
template<class T> struct foo {};
};
struct without_foo {};
int main()
{
assert(has_foo<with_foo>::value);
assert(!has_foo<without_foo>::value);
return 0;
}
实现 has_foo
的最佳方式是什么?
最佳答案
template <template<class> class> using void_templ = void;
template <typename, typename=void> struct has_foo : std::false_type {};
template <typename T>
struct has_foo<T, void_templ<T::template foo>> : std::true_type {};
Demo . GCC 将在这里允许任何类型;那是一个错误。要解决此问题,请将 void_templ
设为类模板
template <template<class> class>
struct void_templ {using type = void;};
Demo .
关于c++ - 如何检查嵌套模板的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28035705/