c++ - 为什么我的 constexpr 函数不能返回 lambda?

标签 c++ c++11 lambda constexpr

我发现这段代码不起作用:

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/

相关文章:

c++ - 使用可变模板的显式模板实例化

c# - 将包含变量的 Lambda 表达式转换为字符串

c++ - 我只想在循环Qt中播放一个mp3文件

c++ - C++ 中哪里可以声明变量?

c++ - 参数化运算符重载

c++ - 在 C++ 中将数字转换为字符串的最佳方法?

java - 带 lambda 表达式的 PriorityQueue<Integer>

java - Java 8 中的递归 lambda 表达式

c++ - SDL2 图像到屏幕问题

c++ - 大型 C++ 项目的 Makefile 模板?