C++:检查模板类型是否是可变参数模板类型之一

Mic*_*hał 5 c++ variadic-templates c++11 c++14 c++17

假设我们有功能:

template <typename Kind, typename... Kinds> void foo(){...};
Run Code Online (Sandbox Code Playgroud)

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

101*_*010 11

您可以使用以下类型特征:

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;
};
Run Code Online (Sandbox Code Playgroud)

现场演示

更新C++ 17

使用C++ 17模式扩展,不再需要辅助类

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
    }
};
Run Code Online (Sandbox Code Playgroud)

现场演示