gpt4 book ai didi

c++ - [C++ 编译时断言] : Can we throw a compilation error if some condition is not met?

转载 作者:可可西里 更新时间:2023-11-01 18:20:19 28 4
gpt4 key购买 nike

我写了一个函数:

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();
}
}

此功能仅在 C++11 之后可用。如果您坚持使用 C++03,请查看 Boost's static assert macro .

整个想法都是很好的错误信息。如果您不关心这些,或者甚至负担不起 boost,您可以执行以下操作:

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++ - [C++ 编译时断言] : Can we throw a compilation error if some condition is not met?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16192575/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com