[英]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.