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 表达式的函数
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
