C ++:检查模板类型是否为可变参数模板类型之一 [英] C++ : Check if the template type is one of the variadic template types

查看:70
本文介绍了C ++:检查模板类型是否为可变参数模板类型之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们具有以下功能:

Let's say we have function:

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

最简单的检查类型是否是 Kinds类型的方法是什么在C ++(包括C ++ 1z)中?

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

实时演示

更新C ++ 17

使用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
    }
};

实时演示

这篇关于C ++:检查模板类型是否为可变参数模板类型之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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