Reputation: 3897
I want to check that a type T
is also part of a parameter pack Ts
. There are solutions that do that in C++14, but I'm wandering if this can be simplified in C++17. If T
is not found in Ts
the compiler should stop (static_assertion should fail).
template<typename... Ts>
class A
{
template<typename T>
void action() {
// check that T is also in Ts (static_assertion)
}
}
Upvotes: 4
Views: 161
Reputation: 61009
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.)
Upvotes: 5
Reputation: 62613
Easy enough in C++ with fold expressions:
template<typename... Ts>
class A
{
template<typename T>
void action() {
static_assert((... || std::is_same_v<T, Ts>)), "Not!")
}
}
Upvotes: 0
Reputation: 303937
I hear fold-expressions are the new hotness:
static_assert((std::is_same_v<T, Ts> || ...));
Upvotes: 6