Using sizeof... within std::enable_if
Asked Answered
J

2

11

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() {
                                         ^
Jen answered 21/1, 2016 at 11:16 Comment(0)
A
18

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
}
Anet answered 21/1, 2016 at 11:18 Comment(2)
Can you give an explanation, please?Semifinalist
@Incubbus I explain the rationale and give a smart ass solution in my answerMassive
M
13

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

Massive answered 21/1, 2016 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.