如何制作可变参数 is_same?

2021-12-13 00:00:00 templates c++ c++11 variadic-templates

我如何制作一个类模板来返回它的任何可变参数类型是否等于第一个类型.我希望能够做到这一点:

How can I make a class template that returns whether any of its variadic types are equal to the first type. I want to be able to do this:

is_same<T, A, B, C>::value; // true if T is one of A, B or C

如果 T 等于这些类型中的任何一种,则其静态 value 成员将为 true,否则 false.我该怎么做?

And if T is equal to any one of those types, its static value member will be true, otherwise false. How can I do this?

推荐答案

使用模板递归:

template<typename T, typename... Rest>
struct is_any : std::false_type {};

template<typename T, typename First>
struct is_any<T, First> : std::is_same<T, First> {};

template<typename T, typename First, typename... Rest>
struct is_any<T, First, Rest...>
    : std::integral_constant<bool, std::is_same<T, First>::value || is_any<T, Rest...>::value>
{};

static_assert(is_any<int, char, double, int>::value, "error 1");   // OK
static_assert(is_any<int, char, double, short>::value, "error 2"); // error

相关文章