Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SFINAE: static_assert vs std::enable_if

Tags:

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

template< typename T > void f() static_assert(std::is_same< T, int >::value) { ; } 

instead of SFINAE (that looks like a crutch):

template< typename T, typename = typename std::enable_if< std::is_same< T, int >::value >::type > void f() { ; } 

or even worse:

template< typename T > typename std::enable_if< std::is_same< T, int >::value >::type  f()  { ; } 

which prohibits using of auto deduction of result type.

like image 756
Tomilov Anatoliy Avatar asked Jun 07 '13 05:06

Tomilov Anatoliy


2 Answers

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)) { ... } 
like image 170
Matthieu M. Avatar answered Oct 02 '22 02:10

Matthieu M.


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()   { } 
like image 32
Jonathan Wakely Avatar answered Oct 02 '22 04:10

Jonathan Wakely