SFINAE: static_assert vs std::enable_if

后端 未结 2 2076
我在风中等你
我在风中等你 2021-02-01 04:51

Are there any disadvantages in the following (suggested!) syntax?

template< typename T >
void f() static_assert(std::is_same< T, int &g         


        
2条回答
  •  不知归路
    2021-02-01 05:43

    First of all, those are different, specifically they are not checked at the same time.

    The critical difference is due to their application with regard to overload resolution. SFINAE will cull functions from the overload set, so that another function gets chosen (if any) whereas static_assert is applied after overload resolution and thus will give an error that will stop compilation.

    Now, regarding your complaint, you can perfectly use auto and SFINAE:

    // Ensure that T is int
    template 
    auto f() -> typename std::enable_if< std::is_same< T, int >::value >::type
    { ... }
    
    // Only pick this overload if begin(c) and end(c) are available
    template 
    auto f(T const& c) -> decltype(begin(c), end(c), bool{}) { ... }
    

    ... and you can perfectly use SFINAE and automatic type deduction

    template ::value>::type>
    auto f() { ... }
    
    template 
    auto f(void* =
           typename std::enable_if::value>::type*(0))
    { ... }
    

提交回复
热议问题