Rét*_*roX 53 c++ static-assert constexpr c++11
如何static_assert
在一个constexpr
函数中正确执行?例如:
constexpr int do_something(int x)
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
Run Code Online (Sandbox Code Playgroud)
这不是有效的C++ 11代码,因为constexpr函数必须只包含return语句.我不认为该标准有例外,但GCC 4.7不允许我编译这段代码.
Joh*_*itb 59
这不是有效的C++ 11代码,因为constexpr函数必须只包含return语句.
这是不正确的.static_assert
在一个constexpr
功能是好的.什么是不好的是在常量表达式中使用函数参数,就像你这样做.
你可以扔掉x <= 0
.在需要常量表达式的上下文中调用该函数将无法编译
constexpr int do_something(int x) {
return x > 0 ? (x + 5) : (throw std::logic_error("x must be > 0"));
}
Run Code Online (Sandbox Code Playgroud)
cpp*_*ist 23
这是有效的C++ 11代码,因为模板参数只是编译时间:
template <int x>
constexpr int do_something() {
static_assert(x > 0, "x must be > 0");
return x + 5;
}
Run Code Online (Sandbox Code Playgroud)
我遇到了与C++中常量表达式相同的问题.目前关于constexprs的文档很少.请注意,在gcc的问题跟踪器中有一些已知的错误,但你的问题似乎不是一个错误.
请注意,如果在类中声明constexpr函数,则无法在类中使用它们.这似乎也不是一个错误.
编辑:根据标准允许这样:7.1.3状态
...或仅包含的复合语句