ton*_*ony 5 c++ templates type-traits template-meta-programming
有许多方法可以实现一个has_type<T>模板,推断出是否T有一个嵌套类或者命名为typedef type.即
namespace detail {
template<typename> struct tovoid { typedef void type; };
}
template<typename T, typename = void> struct has_type
: std::false_type { };
// this one will only be selected if C::type is valid
template<typename C> struct has_type<C, typename detail::tovoid<typename C::type>::type>
: std::true_type { };
Run Code Online (Sandbox Code Playgroud)
要么
template <typename C> char test_for_type(...) { return '0'; }
template <typename C> double test_for_type(typename C::type const *) { return 0.0; }
template <typename T> struct has_type
{
static const bool value = sizeof(test_for_type<T>(0)) == sizeof(double);
};
Run Code Online (Sandbox Code Playgroud)
但在任何一种情况下,都has_type<type>::value属于true这个类:
struct type
{
};
Run Code Online (Sandbox Code Playgroud)
现在上面type没有另外type嵌套在其中,但它确实有一个构造函数type::type().
但是,该构造函数应该"触发"对嵌套类型的检查吗?或者它是编译器错误?(我想这typename type::type不适用于构造函数和/或你不能指向构造函数的指针,例如第二个测试方法会产生什么:typename type::type const *.
?
一类的名字是"注入"类的范围,所以type::type真的是一个类型的名字,这是相同的类型::type.