C++ : Check if the template type is one of the variadic template types [duplicate]

风格不统一 提交于 2019-12-10 14:23:07

问题


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


回答1:


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

Live Demo

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

Live Demo



来源:https://stackoverflow.com/questions/34111060/c-check-if-the-template-type-is-one-of-the-variadic-template-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!