Check if a type is passed in variadic template parameter pack

后端 未结 2 1374
耶瑟儿~
耶瑟儿~ 2020-12-16 01:55

I\'ve heard somewhere, that using new C++1z syntax, it is really easy to check if a type is passed in variadic template parameter pack - apparently you can do this with code

相关标签:
2条回答
  • 2020-12-16 02:39

    If you are bound to C++11 you cannot use std::disjunction nor fold-expressions. However, it is rather straightforward to roll your own any_is_same:

    template<typename same, typename first,typename...more> 
    struct any_is_same {
        static const bool value = std::is_same<same,first>::value || 
                                  any_is_same<first,more...>::value; 
    };
    
    template<typename same,typename first> 
    struct any_is_same<same,first> : std::is_same<same,first> {};
    
    
    int main(){
        std::cout << any_is_same<int, int,double,float>::value << "\n";
        std::cout << any_is_same<std::string, int,double,float>::value << "\n";
    }
    

    Live Demo

    0 讨论(0)
  • 2020-12-16 02:54

    You're looking for std::disjunction. It's specified in N4564 [meta.logical].

    #include <type_traits>
    
    template<typename T, typename... Ts>
    constexpr bool contains()
    { return std::disjunction_v<std::is_same<T, Ts>...>; }
    
    static_assert(    contains<int,      bool, char, int, long>());
    static_assert(    contains<bool,     bool, char, int, long>());
    static_assert(    contains<long,     bool, char, int, long>());
    static_assert(not contains<unsigned, bool, char, int, long>());
    

    Live demo


    Or, adapted to a struct

    template<typename T, typename... Ts>
    struct contains : std::disjunction<std::is_same<T, Ts>...>
    {};
    

    Or, using fold expressions

    template<typename T, typename... Ts>
    struct contains : std::bool_constant<(std::is_same<T, Ts>{} || ...)>
    {};
    

    Live demo

    0 讨论(0)
提交回复
热议问题