在下面的程序中,我在func()中添加了一个显式的return语句,但编译器给出了以下错误:
m.cpp: In function ‘constexpr int func(int)’:
m.cpp:11:1: error: body of constexpr function ‘constexpr int func(int)’ not a return-statement
}
这是代码:
#include
using namespace std;
constexpr int func (int x);
constexpr int func (int x)
{
if (x<0)
x = -x;
return x; // An explicit return statement
}
int main()
{
int ret = func(10);
cout<
return 0;
}
我使用以下命令在g编译器中编译程序.
g++ -std=c++11 m.cpp
我在函数中添加了return语句,然后为什么我出错了?
C 11的constexpr功能比这更具限制性.
从cppreference开始:
the function body must be either deleted or defaulted or contain only the following:
null statements (plain semicolons)
static_assert declarations
typedef declarations and alias declarations that do not define classes or enumerations
using declarations
using directives
exactly one return statement.
所以你可以这样说:
constexpr int func (int x) { return x < 0 ? -x : x; }
static_assert(func(42) == 42, "");
static_assert(func(-42) == 42, "");
int main() {}
请注意,此限制已在C 14中解除.