4

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)
  }
}
O'Neil
  • 3,790
  • 4
  • 16
  • 30
dani
  • 3,677
  • 4
  • 26
  • 60
  • The solution you linked to is 5 lines long. How much simplification are you looking for? – Sneftel Aug 09 '17 at 15:18
  • 1
    My question [here](https://stackoverflow.com/questions/45578484/is-it-possible-to-get-the-first-type-of-a-parameter-pack-in-a-one-liner/45578533#45578533) had four working lines, the answer had only one. Solutions you find here for making a `tuple` of `vector`s of some types in a pack are longer than 10 lines. Its now doable in one. – dani Aug 09 '17 at 15:23
  • @Sneftel, there you go. one-liner. – dani Aug 09 '17 at 15:28
  • There I go indeed. :) – Sneftel Aug 09 '17 at 15:32

3 Answers3

6

I hear fold-expressions are the new hotness:

static_assert((std::is_same_v<T, Ts> || ...));
Barry
  • 286,269
  • 29
  • 621
  • 977
5

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

Columbo
  • 60,038
  • 8
  • 155
  • 203
0

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!")
  }
}
SergeyA
  • 61,605
  • 5
  • 78
  • 137