Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof... within std::enable_if

The following code does not compile, and I just can't figure out why.

template <class T, class... Ts>
typename std::enable_if<sizeof...(Ts) > 0>::type func() {
  // nop
}

The error message produced is:

error: expected unqualified-id before numeric constant
 typename std::enable_if<sizeof...(Ts) > 0u>::type func() {
                                         ^
like image 250
Lingxi Avatar asked Jan 21 '16 11:01

Lingxi


2 Answers

You need parentheses for this to be parsed correctly by the compiler:

template <class T, class... Ts>
typename std::enable_if<(sizeof...(Ts) > 0)>::type func() {
                        ^                 ^
  // nop
}
like image 156
101010 Avatar answered Sep 18 '22 12:09

101010


The compiler interprets the right angle bracket (>) as a closing bracket for std::enable_if. This happens because once you begin a template parameter (or argument) list, the first time, the compiler, has the chance to close it (with >), it does so.

Solution (that proves the above point): Don't close the parameter list, reverse the condition and use a left angle bracket:

template <class T, class... Ts>
typename std::enable_if< 0 < sizeof...(Ts) >::type func() {}
//                         ^ compilers are cool with this

Demo

like image 22
Lorah Attkins Avatar answered Sep 18 '22 12:09

Lorah Attkins