SFINAE: static_assert vs std::enable_if

后端 未结 2 2066
我在风中等你
我在风中等你 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:40

    Why would using static_assert be better than the Concepts Lite syntax?

    template< typename T >
      void f() requires Int<T>()
      { }
    

    or:

    template< Int T >
      void f()
      { }
    
    0 讨论(0)
  • 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 <typename T>
    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 <typename T>
    auto f(T const& c) -> decltype(begin(c), end(c), bool{}) { ... }
    

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

    template <typename T,
              typename = typename std::enable_if<std::is_same<T, int>::value>::type>
    auto f() { ... }
    
    template <typename T>
    auto f(void* =
           typename std::enable_if<std::is_same<T, int>::value>::type*(0))
    { ... }
    
    0 讨论(0)
提交回复
热议问题