What does it mean when one says something is SFINAE-friendly?

后端 未结 2 962
再見小時候
再見小時候 2020-12-24 12:52

I can\'t clearly get the grasp of what it means when one mentions that a particular function, struct or ... is SFINAE-friendly.

Would someone please

2条回答
  •  温柔的废话
    2020-12-24 13:15

    An entity is termed SFINAE-friendly if it can be used in the context of SFINAE without producing a hard error upon substitution failure. I assume you already know what SFINAE is, as that is a whole other question in itself.

    In the context of C++ standardization, the term SFINAE-friendly has so far been applied to std::result_of and std::common_type. Take the following example:

    template 
    void foo(T x, typename std::common_type::type y) {}
    
    void foo(std::string x, std::string y) {}
    
    int main()
    {
        foo(std::string("hello"), std::string("world"));
    }
    

    Without SFINAE-friendly common_type, this would fail to compile, because std::common_type::type would produce a hard error during template argument substitution. With the introduction of SFINAE-friendly common_type (N3843) this example becomes well-formed, because std::common_type::type produces a substitution failure so that overload is excluded from the viable set.

    Here's a similar example with result_of:

    template 
    auto bar(T f) -> typename std::result_of::type { return f(); }
    
    void bar(int n) {}
    
    int main()
    {
        bar(42);
    }
    

    Without SFINAE-friendly result_of, this would fail to compile, because std::result_of::type would produce a hard error during template argument substitution. With the introduction of SFINAE-friendly result_of (N3462) this example becomes well-formed, because std::result_of::type produces a substitution failure so that overload is excluded from the viable set.

提交回复
热议问题