简体   繁体   English

检查模板类型T是否是C ++ 17中可变参数包的一部分

[英]Checking that a template type T is part of a variadic parameter pack in C++17

I want to check that a type T is also part of a parameter pack Ts . 我想检查类型T是否也是参数包Ts There are solutions that do that in C++14, but I'm wandering if this can be simplified in C++17. 有些解决方案可以在C ++ 14中实现,但如果在C ++中可以简化这一点,我就会徘徊17。 If T is not found in Ts the compiler should stop (static_assertion should fail). 如果T中没有找到Ts编译器应该停止(static_assertion应该失败)。

template<typename... Ts>
class A
{
  template<typename T>
  void action() {
    // check that T is also in Ts (static_assertion)
  }
}

我听说折叠表达是新的热点:

static_assert((std::is_same_v<T, Ts> || ...));

If you prefer a library trait: 如果您更喜欢图书馆特质:

static_assert(std::disjunction_v<std::is_same<T, Ts>...>);

Note that this performs short circuiting (perhaps not exceedingly beneficial here, but something to keep in mind). 请注意,这会导致短路(这里可能不是非常有益,但需要注意的事项)。 Fold expressions are equally viable: 折叠表达同样可行:

static_assert((std::is_same_v<T, Ts> || ...));

(Stolen from @Barry.) (从@Barry偷走。)

Easy enough in C++ with fold expressions: 使用折叠表达式在C ++中足够简单:

template<typename... Ts>
class A
{
  template<typename T>
  void action() {
    static_assert((... || std::is_same_v<T, Ts>)), "Not!")
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C++17中模板参数包部分排序规则 - Partial ordering rules of template parameter pack in C++17 C ++ 17中带有参数包的类模板参数推导 - Class template argument deduction with a parameter pack in C++17 我可以在 C++17 中将参数类型分支到参数包吗? - Can I branch on argument type to parameter pack in C++17? C ++ 17 Variadic模板折叠 - C++17 Variadic Template Folding C ++ 17多参数包扩展 - C++17 multiple parameter pack expansion C++17 可以可变参数模板 class 定义新的类型和可变参数数据成员吗? - C++17 can variadic template class define new type and variadic data member? C ++ 17,为什么自动非类型模板参数不能与SFINAE一起使用 - C++17, why doesn't auto non-type template parameter work with SFINAE 如何在C ++ 17中创建一个从变量模板推导出的类型向量元组? - How to create a tuple of vectors of type deduced from a variadic template in C++17? C ++ 17:通用(基于多继承?)检查参数包中的模板 - C++17: Generic (multiple-inheritance based?) check for template in parameter pack C++17 如何使用可变参数模板模仿 Julia 的“promote_type” function - C++17 How to mimic Julia's 'promote_type' function using variadic template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM