Function returning a lambda expression(返回 lambda 表达式的函数)
问题描述
我想知道是否可以在 C++11 中编写一个返回 lambda 函数的函数.当然一个问题是如何声明这样的函数.每个 lambda 都有一个类型,但该类型在 C++ 中无法表达.我认为这行不通:
auto retFun() ->decltype ([](int x) -> int){返回 [](int x) { 返回 x;}}
也不是这个:
int(int) retFun();
我不知道从 lambda 表达式到函数指针等的任何自动转换.手工制作函数对象并返回它的唯一解决方案是什么?
你不需要手工制作的函数对象,只需使用 std::function
,lambda 函数可以转换为:>
此示例返回整数标识函数:
std::functionretFun() {返回 [](int x) { 返回 x;};}
I wonder if it's possible to write a function that returns a lambda function in C++11. Of course one problem is how to declare such function. Each lambda has a type, but that type is not expressible in C++. I don't think this would work:
auto retFun() -> decltype ([](int x) -> int)
{
return [](int x) { return x; }
}
Nor this:
int(int) retFun();
I'm not aware of any automatic conversions from lambdas to, say, pointers to functions, or some such. Is the only solution handcrafting a function object and returning it?
You don't need a handcrafted function object, just use std::function
, to which lambda functions are convertible:
This example returns the integer identity function:
std::function<int (int)> retFun() {
return [](int x) { return x; };
}
这篇关于返回 lambda 表达式的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回 lambda 表达式的函数


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01