4 ms·
The more readable C++11 version would use static_assert: template <size_t N> foo(int (&bar)[N]) { static_assert(N >= 10, "Array needs >=
by pbsd 14y ago
The more readable C++11 version would use static_assert:
template <size_t N>
foo(int (&bar)[N])
{
static_assert(N >= 10, "Array needs >= 10 elements!");
...
}
- pyrtsa 14y agoCorrect. The key difference is that the enable_if version can be overloaded with mutually exclusive requirements: template <size_t N> typename enable_if<(1 < N && N < 10), void>::type foo(int (&bar)[N]) { // called when 1 < N && N < 10 } template <size_t N> typename enable_if<(N >= 10), void>::type foo(int (&bar)[N]) { // called when N >= 10 } OTOH, the key advantage in static_assert is the meaningful error message.
- abcd_f 14y agoThis will generate separate function bodies for different values of N.
- zokier 14y agoI don't think that is more readable. With enable_if the precondition is clearly visible at the function header, while the static_assert is inside the body and thus more easily accidentally ignored.
- obiterdictum 14y agoOn the other hand, static_assert will have a more helpful compile error for users of the code. They will clearly see assertion condition that failed, rather than missing candidate error due to substitution failure (or worse, a different overload silently considered instead).