Approaches to function SFINAE in C++

前端 未结 2 726
悲&欢浪女
悲&欢浪女 2021-01-31 02:41

I am using function SFINAE heavily in a project and am not sure if there are any differences between the following two approaches (other than style):

#include &l         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 02:56

    In addition to max66's answer, another reason to prefer method 2 is that with method 1, you can (accidentally) pass an explicit type parameter as the second template argument and defeat the SFINAE mechanism completely. This could happen as a typo, copy/paste error, or as an oversight in a larger template mechanism.

    #include 
    #include 
    #include 
    
    // NOTE: foo should only accept T=int
    template >>
    void foo(){
        std::cout << "method 1" << std::endl;
    }
    
    int main(){
    
        // works fine
        foo();
    
        // ERROR: subsitution failure, as expected
        // foo();
    
        // Oops! also works, even though T != int :(
        foo();
    
        return 0;
    }
    

    Live demo here

提交回复
热议问题