如何制作可变参数 is_same? [英] How to make a variadic is_same?

查看:31
本文介绍了如何制作可变参数 is_same?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何制作可变参数 is_same?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆