SFINAE works differently in cases of type and non-type template parameters

后端 未结 5 470
遇见更好的自我
遇见更好的自我 2020-11-28 13:25

Why does this code work:

template<
    typename T, 
    std::enable_if_t::value, T>* = nullptr>
void Add(T) {}

templa         


        
5条回答
  •  半阙折子戏
    2020-11-28 14:13

    I'll try to first give an example without the use of templates, but with default arguments. The following example is comparable to why the second example of yours fails, although it is not indicative of the inner workings of template overload resolution.

    You have two functions declared as such:

    void foo(int _arg1, int _arg2 = 3);
    

    And

    void foo(int _arg1, int _arg2 = 4);
    

    Hopefully you realize that this will fail to compile, their is never going to be a way to distinguish between the two calls to foo with the default argument. It's completely ambiguous, how will the compiler ever know which default to choose? You may wonder why i used this example, after all shouldn't the template in the first example deduce different types? The short answer to that is no, and that's because the "signature" of the two templates in your second example:

    template<
        typename T, 
        typename = typename std::enable_if::value, T>::type>
    void Add(T) {}
    
    template<
        typename T, 
        typename = typename std::enable_if::value, T>::type>
    void Add(T) {}
    

    ...have the exact same signature, which is:

    template
    void Add(T);
    

    And (respectively)

    template 
    void Add(T); 
    

    Now you should start to understand the similarity's between the example i gave with non-templates and the example you provided that failed.

提交回复
热议问题