c++ 1y/14: constexpr函数中的错误处理
C++1y/14: Error handling in constexpr functions?
假设我想写一个c++ 1y/14 constexpr函数来执行整数平方根:
constexpr int constexpr_isqrt(int x);
我想执行一个完整性检查以确保x
是非负的:
constexpr int constexpr_isqrt(int x)
{
if (x < 0)
???
...
}
我应该在上面的???
中写什么?
理想情况下,如果函数在常量上下文中求值,应该会导致编译时错误,如果在运行时调用,则会导致运行时错误(例如abort或抛出异常)。
你很幸运,有办法!甚至在c++ 11中!使用例外:
#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++中可靠地获得用户十六进制输入
- posix_spawn():使用posix_scawn()时的错误处理问题
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 关于 istream 中的错误处理的问题
- 程序使用的 C 库中的错误处理C++
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 使用std::tie进行类似golang的错误处理,同时返回结果,是否有缺点?(C++11)
- Boost进程"系统"功能中的错误处理
- RPN计算器c++错误处理和多个运算符
- 提升精神 x3 错误处理程序与期望
- 构造函数中的错误处理而不会失败
- 当 C++ 中函数参数的输入类型(类)错误时的错误处理
- 关于 ocilib 错误处理的问题,如何使用 ocilib 正确捕获日志错误?
- 我可以使用 std::optional 进行错误处理吗?
- C++ main() 末尾关于错误处理的错误
- 抽象包装带有异常的 C 错误处理的最佳方法
- vwprintf错误处理(ERRNO显示0)
- C++ 使用枚举进行错误处理
- 在 C++ 中创建自己的错误处理机制