How to make a variadic is_same?

后端 未结 6 785
刺人心
刺人心 2020-12-05 02:07

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

        
6条回答
  •  清歌不尽
    2020-12-05 03:10

    Something like this. First, a small metaprogramming library, because it adds like 2 lines to do it generically:

    templateclass checker, typename... Ts>
    struct is_any_to_first : std::false_type {};
    
    templateclass checker, typename T0, typename T1, typename... Ts>
    struct is_any_to_first :
      std::integral_constant< bool, checker::value || is_any_to_first::value>
    {};
    

    Then a 2 line implementation of is_any_same_to_first:

    template
    using is_any_same_to_first = is_any_to_first< std::is_same, Ts... >;
    

    And for completeness, the original is_all, which may also prove useful:

    templateclass checker, typename... Ts>
    struct is_all : std::true_type {};
    
    templateclass checker, typename T0, typename T1, typename... Ts>
    struct is_all :
      std::integral_constant< bool, checker::value && is_all::value>
    {};
    
    template
    using is_all_same = is_all< std::is_same, Ts... >;
    

    Live example of the is_all_same.

    Note that calling is_any_same_to_first anything less explicit is asking for trouble. 2/3 people who tried to answer this question, including me, assumed that is_same is true iff all three are the same type!

提交回复
热议问题