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 表达式的函数
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
