gpt4 book ai didi

C++1y/14 : Error handling in constexpr functions?

转载 作者:可可西里 更新时间:2023-11-01 16:36:23 25 4
gpt4 key购买 nike

假设我想编写一个执行整数平方根的 C++1y/14 constexpr 函数:

constexpr int constexpr_isqrt(int x);

我想执行完整性检查以确保 x 是非负数:

constexpr int constexpr_isqrt(int x)
{
if (x < 0)
???

...
}

上面的???应该写什么?

理想情况下,如果函数是在常量上下文中计算的,它应该会导致编译时错误,如果在运行时调用时会出现运行时错误(例如中止或抛出异常)。

最佳答案

你很幸运,有办法!即使在 C++11 中!使用异常(exception):

#include <iostream>
#include <stdexcept>

constexpr int foo(int a)
{
return (a >= 0) ? a : throw std::invalid_argument("Negative!");
}

template <int n>
struct Foo
{
};

int main()
{
Foo<foo(1)> f1(); // fine, guaranteed compile time
Foo<foo(-1)> f2(); // bad, compile time error
foo(1); // fine, not necessarily at compile time
try
{
foo(-1); // fine, definitively not at compile time
}
catch ( ... )
{
}
return 0;
}

演示:http://ideone.com/EMxe2K

GCC 对于不允许的情况有一个相当好的错误消息:

prog.cpp: In function ‘int main()’:
prog.cpp:17:12: in constexpr expansion of ‘foo(-1)’
prog.cpp:6:63: error: expression ‘<throw-expression>’ is not a constant-expression
return (a >= 0) ? a : throw std::invalid_argument("Negative!");

对于看起来像的 C++1y constexpr 函数

constexpr foo(int a)
{
if ( a < 0 )
{
// error!
}
++a;
//something else
return a;
}

你可以通过引入一个新函数来使用上面的模式:

constexpr foo_positive(int a)
{
++a;
//something else
return a;
}

constexpr int foo(int a)
{
return (a >= 0) ? foo_positive(a) : throw std::invalid_argument("Negative!");
}

或者你只是写

constexpr foo(int a)
{
if ( a < 0 )
{
throw std::invalid_argument("Negative!");
}
++a;
//something else
return a;
}

关于C++1y/14 : Error handling in constexpr functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22321612/

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