【问题标题】:constexpr with conditional statement error, using Stroustrup example带有条件语句错误的 constexpr,使用 Stroustrup 示例
【发布时间】:2020-10-01 19:12:03
【问题描述】:

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
 }

【问题讨论】:

  • 我强烈建议您选择更新的参考。此代码 (bad2) 在 c++11 中无效,但在 c++14 中有效。
  • 谢谢。我添加了编译结果。 C++11 是否仅在某些类型的条件下导致错误?似乎在 g++ 默认 C 标准中已解决,即 C++14?
  • 我不是 100% 确定,但 ifstatement?: 是一个表达式,因此不允许使用语句(除了单个返回),但表达式是(你可以嵌套?:)。

标签: c++ c++11 c++14 constexpr


【解决方案1】:

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

(C++14 前)

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

所以在 C++14 之前,通常使用条件运算符(而不是 if)和递归(而不是循环),并在单个 return 语句中约束 constexpr 函数。

从 C++14 开始使用 if 语句,允许多个 return 语句和循环。

【讨论】:

  • RE:在 C++14 之前,是 'return (cond) 吗? x : y' 允许的条件的特殊情况?
  • @notaorb 使用条件运算符很好;并且满足只有一个return语句的要求。
猜你喜欢
  • 2015-07-21
  • 2021-01-27
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 2015-07-29
相关资源
最近更新 更多