我发现这段代码不起作用:
typedef int (*fp)(int a, int b);
constexpr fp addition()
{
return [](int a, int b){ return a+b; };
}
#include <iostream>
int main()
{
fp fun = addition();
std::cout << fun(2,2);
}
它给了我错误
cexpr.cpp: In function 'constexpr int (* addition())(int, int)':
cexpr.cpp:5:43: error: call to non-constexpr function 'addition()::<lambda(int,
int)>::operator int (*)(int, int)() const'
这是为什么呢?我这里不叫它。
直接方法有效:
typedef int (*fp)(int a, int b);
#include <iostream>
int main()
{
fp fun = [](int a, int b){ return a+b; };
std::cout << fun(2,2);
}
我正在使用带有 g++ 版本 4.7.2 的 MinGW。
最佳答案
您的函数 fp()
不返回文字类型,因此它不能是 constexpr 函数:
From 7.1.5: "The definition of a constexpr function shall satisfy the following constraints:
- it shall not be virtual (10.3);
- its return type shall be a literal type;
- each of its parameter types shall be a literal type;
- its function-body shall be = delete, = default, or a compound-statement that contains only
- null statements,
- static_assert-declarations
- typedef declarations and alias-declarations that do not define classes or enumerations,
- using-declarations,
- using-directives,
- and exactly one return statement;"
我认为这里没有任何错误,尤其是之前的回答中提到的与 lambdas 无关的东西:变量根本无法在 constexpr 函数中声明。
关于c++ - 为什么我的 constexpr 函数不能返回 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085956/