template <int number1>
typename boost::enable_if_c< (number1 >= 10) >::type
reportErrorIfLessThan10() {
// ...
}
The above enable_if
, without the _c because we have a plain bool, looks like this:
template<bool C, typename T = void>
struct enable_if {
typedef T type;
};
template<typename T>
struct enable_if<false, T> { };
Boost's enable_if
takes not a plain bool, so they have another version which has a _c appended, that takes plain bools. You won't be able to call it for number1
< 10. SFINAE will exclude that template as possible candidates, because enable_if
will not expose a type ::type
if the condition evaluates to false
. If you want, for some reason, test it in the function, then if you have the C++1x feature available, you can use static_assert
:
template <int number1>
void reportErrorIfLessThan10() {
static_assert(number >= 10, "number must be >= 10");
}
If not, you can use BOOST_STATIC_ASSERT:
template <int number1>
void reportErrorIfLessThan10() {
BOOST_STATIC_ASSERT(number >= 10);
}
The only way to display a descriptive message is using static_assert, though. You can more or less simulate that, using types having names that describe the error condition:
namespace detail {
/* chooses type A if cond == true, chooses type B if cond == false */
template <bool cond, typename A, typename B>
struct Condition {
typedef A type;
};
template <typename A, typename B>
struct Condition<false, A, B> {
typedef B type;
};
struct number1_greater_than_10;
}
template <int number1>
void reportErrorIfLessThan10() {
// number1 must be greater than 10
sizeof( typename detail::Condition< (number1 >= 10),
char,
detail::number1_greater_than_10
>::type );
}
It prints this here:
error: invalid application of 'sizeof' to incomplete type 'detail::number1_greater_than_10'
But I think the very first approach, using enable_if
will do it. You will get an error message about an undeclared reportErrorIfLessThan10
.