dani
dani

Reputation: 3897

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. 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 Tsthe 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

Answers (3)

Columbo
Columbo

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

SergeyA
SergeyA

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

Barry
Barry

Reputation: 303937

I hear fold-expressions are the new hotness:

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

Upvotes: 6

Related Questions