本文介绍了constexpr函数的主体不是返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的程序中,我在 func()
中添加了显式的 return
语句,但是编译器给出了我出现以下错误:
In the following program, I have added an explicit return
statement in func()
, but the compiler gives me the following error:
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 <iostream>
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<<ret<<endl;
return 0;
}
我已经在 g ++ 编译器中使用以下命令。
I have compiled program in a g++ compiler using the following command.
g++ -std=c++11 m.cpp
我在函数中添加了 return
语句,然后为什么会出现上述错误? / strong>
I have added return
statement in function, then Why I got above error?
推荐答案
C ++ 11的 constexpr
函数更具限制性
C++11's constexpr
functions are more restrictive than that.
来自:
- 空语句(普通分号)
-
static_assert
声明 -
typedef
声明和没有定义类或枚举的别名声明 -
using
声明 -
使用
目录 - 恰好是一个
return
语句。
- null statements (plain semicolons)
static_assert
declarationstypedef
declarations and alias declarations that do not define classes or enumerationsusing
declarationsusing
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。
Note that this restriction was lifted in C++14.
这篇关于constexpr函数的主体不是返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!