12

Let's say we have function:

template <typename Kind, typename... Kinds> void foo(){...};

What is the simplest way to check if the type 'Kind' is one of the types 'Kinds' in C++ (including C++1z)?

Michał
  • 655
  • 6
  • 19
  • 1
    This particular question has been asked at least three times in the past few days... – T.C. Dec 05 '15 at 21:25

1 Answers1

23

You could use the following type trait:

template <typename...>
struct is_one_of {
    static constexpr bool value = false;
};

template <typename F, typename S, typename... T>
struct is_one_of<F, S, T...> {
    static constexpr bool value =
        std::is_same<F, S>::value || is_one_of<F, T...>::value;
};

Live Demo

Update C++17

Using the C++17 pattern expansion there is no need for auxiliar class anymore

template <typename Kind, typename... Kinds> void foo(){
    /* The following expands to :
     * std::is_same_v<Kind, Kind0> || std::is_same_v<Kind, Kind1> || ... */
    if constexpr ((std::is_same_v<Kind, Kinds> || ...)) {
        // expected type
    } else {
        // not expected type
    }
};

Live Demo

barsdeveloper
  • 930
  • 8
  • 28
101010
  • 41,839
  • 11
  • 94
  • 168