template <int number1>
typename boost::enable_if_c< (number1 >= 10) >::type
reportErrorIfLessThan10() {
// ...
}
上面的enable_if,没有_c,因为我们有一个普通的布尔值,看起来像这样:
template<bool C, typename T = void>
struct enable_if {
typedef T type;
};
template<typename T>
struct enable_if<false, T> { };
Boost 的enable_if 不采用纯布尔值,因此他们有另一个附加了 _c 的版本,它采用纯布尔值。您将无法为 number1 SFINAE 将排除该模板作为可能的候选对象,因为如果条件评估为 @,enable_if 将不会公开类型 ::type 987654330@。如果你想,出于某种原因,在函数中测试它,那么如果你有C++1x 功能可用,你可以使用static_assert:
template <int number1>
void reportErrorIfLessThan10() {
static_assert(number >= 10, "number must be >= 10");
}
如果没有,你可以使用 BOOST_STATIC_ASSERT:
template <int number1>
void reportErrorIfLessThan10() {
BOOST_STATIC_ASSERT(number >= 10);
}
不过,显示描述性消息的唯一方法是使用 static_assert。您可以或多或少地模拟这一点,使用具有描述错误条件的名称的类型:
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 );
}
它在这里打印:
错误:“sizeof”对不完整类型“detail::number1_greater_than_10”的无效应用
但我认为第一种方法,使用enable_if 就可以了。您将收到关于未声明的reportErrorIfLessThan10 的错误消息。