[C ++编译时断言]:如果不满足某些条件,我们可以抛出编译错误吗? [英] [C++ compile time assertions]: Can we throw a compilation error if some condition is not met?
本文介绍了[C ++编译时断言]:如果不满足某些条件,我们可以抛出编译错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个函数:
template<int N> void tryHarder() {
for(int i = 0; i < N; i++) {
tryOnce();
}
}
但是我只希望在N在0到10之间的情况下进行编译.我可以这样做吗?怎么样?
but I only want it to compile if N is in between 0 and 10. Can I do it? How?
推荐答案
您可以使用 static_assert
声明进行操作:
You can do it with 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();
}
}
此功能仅在C ++ 11起可用.如果您使用的是C ++ 03,请看看 Boost的静态断言宏.
This feature is only avaliable since C++11. If you're stuck with C++03, take a look at Boost's static assert macro.
这的整个想法都是不错的错误消息.如果您不关心这些东西,或者甚至无法提高自己的能力,则可以执行以下操作:
The whole idea of this are nice error messages. If you don't care for those, or can't even affor boost, you could do something as follows:
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
}
这篇关于[C ++编译时断言]:如果不满足某些条件,我们可以抛出编译错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文