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)?
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)?
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;
};
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
}
};