加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – constexpr函数的主体不是return语句

发布时间:2020-12-16 10:53:52 所属栏目:百科 来源:网络整理
导读:在下面的程序中,我在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 } 这是代码: #in
在下面的程序中,我在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 <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编译器中编译程序.

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中解除.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读