返回lambda表达式的函数 [英] Function returning a lambda expression

查看:124
本文介绍了返回lambda表达式的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以编写一个函数来返回一个lambda函数在C ++ 11。当然一个问题是如何声明这样的函数。每个lambda都有一个类型,但该类型在C ++中不可表达。我不认为这会工作:

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; }
}

也不是这样:

int(int) retFun();

我不知道从lambdas到例如指向函数的指针的自动转换,这样。是唯一的解决方案手工制作一个函数对象并返回吗?

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?

推荐答案

您不需要手工制作的函数对象,只需使用 std :: function ,其中lambda函数可以转换:

You don't need a handcrafted function object, just use std::function, to which lambda functions are convertible:

std::function<int (int)> retFun() {
    return [](int x) { return x; };
}

这篇关于返回lambda表达式的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆