【问题标题】:Type trait test if template parameter is some instantiation of another template如果模板参数是另一个模板的某个实例化,则类型特征测试
【发布时间】:2018-10-10 21:24:25
【问题描述】:

假设在下面的代码中,意图是允许Bar<T> 中的T 成为任何UFoo<U>

template<typename U>
class Foo { };

template<typename T, typename = std::enable_if_t< /*T is Foo<U> for any U*/>>
class Bar {
    // ...
};

我用什么替换 /*T is Foo&lt;U&gt; for any U*/ 吗?

【问题讨论】:

  • @Barry 我看到了您的编辑,但额外的条件是为了避免不回答的建议,例如 template&lt;typename U&gt;class Bar{ using T=Foo&lt;U&gt;; }
  • 为什么会有人这么建议?这似乎对这个问题没有帮助。
  • @Barry 有了你的代表,人们不会再猜测你真正想问的问题,但我已经学会在我的问题中构建抗失真机制。
  • 如果您认为编辑违背了问题的意图,我们非常欢迎您回滚编辑 - 但我想了解您正在尝试哪种“不回答建议”避免得到。
  • @Barry 这并没有违背问题的意图——事实上这正是问题最初的起草方式。

标签: c++ c++14 sfinae typetraits enable-if


【解决方案1】:

您可以编写一个通用特征来匹配任何专业:

template <typename T, template <typename...> class Z>
struct is_specialization_of : std::false_type { };

template <typename... Args, template <typename....> class Z>
struct is_specialization_of<Z<Args...>, Z> : std::true_type { };

在您的具体情况下是:

is_specialization_of<T, Foo>::value // <== T is some kind of Foo

【讨论】:

    【解决方案2】:

    您可以为此创建一个特征:

    template <typename T>
    struct is_foo : std::false_type {};
    
    template <typename T>
    struct is_foo<Foo<T>> : std::true_type {};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2011-05-10
      • 1970-01-01
      相关资源
      最近更新 更多