带有条件语句错误的constexpr,使用Stroustrup示例

问题描述 投票:3回答:1

Stroustrup C ++第4版。页面311描述了阶乘的constexpr fac,其中包括一个条件语句。然后在第312页上,用条件语句和注释说明constexpr bad2,该注释会导致错误。他还在第312页指出“ constexpr函数允许递归和条件表达式。”

两个函数和导致错误的条件语句之间有什么区别?

#include <iostream>
using namespace std;

constexpr int fac(int n)
{
    return (n > 1) ? n*fac(n-1) : 1;
}

constexpr int bad2(int a)
{
    if (a>=0) return a; else return -a; // error: if-statement in constexpr function
}

int main(int argc, char *argv[])
{
    constexpr int c = 3;
    cout << fac(c) << endl;
    cout << bad2(c) << endl;

    return 0;
}

汇编和结果:

g++ -pedantic -Wall test135.cc && ./a.out
6
3

[bad2的确在C ++ 11模式下导致错误。

g++ -pedantic -Wall -std=c++11 test135.cc && ./a.out
test135.cc: In function ‘constexpr int bad2(int)’:
test135.cc:12:1: error: body of ‘constexpr’ function ‘constexpr int bad2(int)’ not a return-statement
 }
c++ c++11 c++14 constexpr
1个回答
2
投票

在C ++ 14之前,if语句不能在constexpr functions中使用,它可能只有一个constexpr语句。

(直到C ++ 14)

  • 该功能正文必须删除或默认,或者仅包含以下内容:
    • 空语句(普通分号)
    • static_assert声明
    • 没有定义类或枚举的typedef声明和别名声明
    • 使用声明
    • 使用指令
    • 如果函数不是构造函数,则只返回一个返回语句

因此,直到C ++ 14,通常使用条件运算符(而不是return)和递归(而不是循环),并且将单个if语句约束为return函数。

由于C ++ 14使用constexpr语句,所以允许多个if语句和循环。

© www.soinside.com 2019 - 2024. All rights reserved.