gpt4 book ai didi

c++ - 有条件地指定 noexcept 函数

转载 作者:行者123 更新时间:2023-12-04 11:58:21 25 4
gpt4 key购买 nike

假设我声明了这样的函数 noexcept :

int pow(int base, int exp) noexcept
{
return (exp == 0 ? 1 : base * pow(base, exp - 1));
}
从我很少但逐渐增长的 C++ 知识中,我可以 noexcept当我确定该函数不会抛出异常时。我还了解到它可以在某个值范围内,假设我考虑了我的函数 noexceptexp小于 10,且 base小于 8(仅作为示例)。我如何声明这个函数是 noexcept在这样的值范围内?或者我能做的最多就是给其他程序员留言说它应该在某些范围内?

最佳答案

您可以为 noexcept 使用条件,但该条件必须是一个常量表达式。它不能依赖于传递给函数的参数的值,因为它们只有在调用函数时才知道。
来自 cppreference/noexcept :

Every function in C++ is either non-throwing or potentially throwing


它不能两者兼有,也不能介于两者之间。在你的例子中,我们可以制作 base模板参数:
template <int base>
int pow(int exp) noexcept( base < 10)
{
return (exp == 0 ? 1 : base * pow<base>(exp - 1));
}
现在 pow<5>是一个不抛出的函数,而 pow<10>是一个可能会抛出的函数。

关于c++ - 有条件地指定 noexcept 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69117249/

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