我写了一个函数:[C++编译时断言]:如果不满足某些条件,我们可以抛出一个编译错误吗?
template<int N> void tryHarder() {
for(int i = 0; i < N; i++) {
tryOnce();
}
}
但我只希望它来编译,如果N是介于0和10.我能做到吗?怎么样?
我写了一个函数:[C++编译时断言]:如果不满足某些条件,我们可以抛出一个编译错误吗?
template<int N> void tryHarder() {
for(int i = 0; i < N; i++) {
tryOnce();
}
}
但我只希望它来编译,如果N是介于0和10.我能做到吗?怎么样?
你可以用static_assert
declaration做到这一点:
template<int N> void tryHarder() {
static_assert(N >= 0 && N <= 10, "N out of bounds!");
for(int i = 0; i < N; i++) {
tryOnce();
}
}
此功能只avaliable因为C++ 11。如果你坚持使用C++ 03,请看。
这是一个很好的错误信息。如果你不关心这些,或者甚至不能AFFOR提升,你可以做一些事情如下:
template<bool B>
struct assert_impl {
static const int value = 1;
};
template<>
struct assert_impl<false> {
static const int value = -1;
};
template<bool B>
struct assert {
// this will attempt to declare an array of negative
// size if template parameter evaluates to false
static char arr[assert_impl<B>::value];
};
template<int N>
void tryHarder()
{
assert< N <= 10 >();
}
int main()
{
tryHarder<5>(); // fine
tryHarder<15>(); // error, size of array is negative
}
#if !defined(__cplusplus)
#error C++ compiler required.
#endif
这仅仅是一个例子。
这里是源链接:http://msdn.microsoft.com/en-us/library/c8tk0xsk(v=vs.71).aspx
我要说的是,你可以使用#ERROR也
这是一个指令
编辑@Pratik Chowdhruy:我同意保罗R.这不直接回答这个问题。对不起,社区
这不回答这个问题。 – 2013-04-24 13:01:20
看看其他答案,了解问题出在这里--OP想知道如何对模板参数进行编译时断言,而不是如何使用条件编译和'#error'。 – 2013-04-24 13:24:24
对不起保罗R – 2013-05-16 16:31:20
对于预C++ 11个编译器,可以实现对非类型参数N.
对于如何做到这一点的描述模板参数限制,请参见http://stroustrup.com/bs_faq2.html#constraints
看看[static_assert](http://en.cppreference.com/w/cpp/language/static_assert) – juanchopanza 2013-04-24 12:56:04
@juanchopanza:这就是答案。 – Nawaz 2013-04-24 12:57:08
它看起来不错!但是,有什么预先C++ 11? – MciprianM 2013-04-24 13:03:40