constexpr函数的主体不是return语句

msc*_*msc 5 c++ function return-type constexpr c++11

在下面的程序中,我添加了一个显式return语句func(),但编译器给出了以下错误:

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
 }
Run Code Online (Sandbox Code Playgroud)

这是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我使用以下命令在g ++编译器中编译了程序.

g++ -std=c++11 m.cpp
Run Code Online (Sandbox Code Playgroud)

return在函数中添加了语句,然后为什么我出现上述错误?

Tho*_*mas 13

在C++ 14之前,constexpr函数体必须只包含一个return语句:它内部不能包含任何其他语句.这适用于C++ 11:

constexpr int func (int x) 
{
  return x < 0 ? -x : x;
}
Run Code Online (Sandbox Code Playgroud)

在C++ 14及更高版本中,您编写的内容与大多数其他语句一样合法.

资源.


mpa*_*ark 11

C++ 11的constexpr功能比这更具限制性.

cppreference:

函数体必须删除或默认,或仅包含以下内容:

  • 空语句(普通分号)
  • static_assert 声明
  • typedef 声明和别名声明,不定义类或枚举
  • using 声明
  • using 指令
  • 一个return陈述.

所以你可以这样说:

constexpr int func (int x) { return x < 0 ? -x : x; }

static_assert(func(42) == 42, "");
static_assert(func(-42) == 42, "");

int main() {}
Run Code Online (Sandbox Code Playgroud)

请注意,此限制已在C++ 14中解除.