gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:22:39 24 4
gpt4 key购买 nike

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++ 14之前, if functions不能使用constexpr语句,它可能恰好只有一个return语句。

(直到C++ 14)

  • 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
    • if the function is not a constructor, exactly one return statement


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

由于C++ 14使用 if语句,因此允许多个 return语句和循环。

关于c++ - 带有条件语句错误的constexpr,使用Stroustrup示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62336297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com