我想写一个类型特征来检测一个类型是否有一个 T::type
某种类型的。我使用的是 代码从这个答案. 这是我使用的部分代码,供参考。
// See http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4502.pdf. template <typename...> using void_t = void; // Primary template handles all types not supporting the operation. template <typename, template <typename> class, typename = void_t<>> struct detect : std::false_type {}; // Specialization recognizes/validates only types supporting the archetype. template <typename T, template <typename> class Op> struct detect<T, Op, void_t<Op<T>>> : std::true_type {};
我从简单的特征开始,用一个特质来检测 T::type
:
template <typename T>
using has_type_t = typename T::type;
template <typename T>
using has_type = detect<T, has_type_t>;
这和预期的一样,但是当我问到实际的类型时。T::type
我也得到了我不理解的错误。
template <typename X>
struct has_X_type_helper {
template <typename T>
using type = typename std::enable_if_t<std::is_same_v< typename T::type, X>,int>;
};
template <typename T,typename X>
using has_X_type = detect<T,has_X_type_helper<X>::type>;
GCC:
<source>:49:55: error: type/value mismatch at argument 2 in template parameter list for 'template<class, template<class> class<template-parameter-1-2>, class> struct detect'
49 | using has_X_type = detect<T,has_X_type_helper<X>::type>;
| ^
<source>:49:55: note: expected a class template, got 'has_X_type_helper<X>::type'
而Clang对我来说更加混乱了
<source>:49:29: error: template argument for template template parameter must be a class template or type alias template
using has_X_type = detect<T,has_X_type_helper<X>::type>;
^
是 has_X_type_helper<X>::type
不是类型别名模板?我的代码有什么问题?
你需要说明嵌套的东西是一个模板。
template <typename T, typename X>
using has_X_type = detect<T, has_X_type_helper<X>::template type>;
// ~~~~~~~~~^