【问题标题】:alias template is not a class template?别名模板不是类模板吗?
【发布时间】:2021-12-18 16:59:46
【问题描述】:

我正在尝试编写一个类型特征来检测一个类型是否具有某种类型的T::type。我正在使用code from this answer。作为参考,这是我正在使用的代码的一部分:

// 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>;

海合会:

<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&lt;X&gt;::type 不是类型别名模板吗?我的代码有什么问题?

@ godbolt

【问题讨论】:

    标签: c++ templates typetraits


    【解决方案1】:

    你需要指出嵌套的东西是一个模板:

    template <typename T, typename X>
    using has_X_type = detect<T, has_X_type_helper<X>::template type>;
    //                                               ~~~~~~~~~^
    

    【讨论】:

    • 我认为这是我最不直观的语法列表中的新顶部。是否需要因为has_X_type_helper 是模板?还是因为has_X_type_helper&lt;X&gt;::type 是一个模板?我还是觉得有点混乱,因为has_X_type_helper&lt;X&gt; 只是一个类型,has_X_type_helper&lt;X&gt;::type 是一个模板,就像has_type_t 是一个模板一样
    • 啊,我想我明白了。 has_X_type_helper 可能有特化,所以我需要向编译器保证 type 是一个模板
    • @idclev463035818 是的,这与typename 的故事相同。否则,编译器假定它是一个类似std::is_const&lt;T&gt;::value 的值,因此它报告'type/value mismatch'
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    相关资源
    最近更新 更多