Matching variadic non-type templates

后端 未结 3 1903
予麋鹿
予麋鹿 2021-02-18 14:13

Let\'s say I have two structs, Foo and Bar:

template
struct Foo{};

template
struct Bar{};
         


        
3条回答
  •  广开言路
    2021-02-18 14:41

    Question: What is a workaround for this in C++14?

    A possible workaround in C++14 is based on traits.
    As a minimal, working example (maybe even stupid, but it helps getting the idea):

    #include 
    #include 
    
    template
    struct Foo{};
    
    template
    struct Bar{};
    
    template
    struct traits;
    
    template
    struct traits> { using type = Foo<0>; };
    
    template
    struct traits> { using type = Bar<0>; };
    
    template
    constexpr bool match = std::is_same::type, typename traits::type>::value;
    
    int main() {
        using f1 = Foo<1, 2, 3>;
        using f2 = Foo<1>;
        using b1 = Bar<1, 2, 3>;
        using b2 = Bar<1>;
    
        static_assert(match, "Fail");
        static_assert(match, "Fail");
        static_assert(!match, "Fail");
    }
    

    As a side note, in C++17 you can simplify things up as it follows:

    template class S, auto... U, auto... V>
    struct match_class, S> : std::true_type{};
    

    About the reasons that are behind the error, @Barry's answer contains all what you need to understand it (as usual).

提交回复
热议问题