如何返回lambda对象? [英] How can I return a lambda object?

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

问题描述

我想从函数返回一个lambda对象,而不将其强制转换为函数指针或函数对象。更具体地说,我想让它留给客户端来决定是否强制转换为函数对象或将lambda保留为匿名函数:

I want to return a lambda object from a function without casting it to a function pointer or function object. More specifically, I want to leave it to the client to decide whether or not to cast to a function object or retain the lambda as an anonymous function:

template<typename F> // F may be a std::function, boost::function, or lambda object
auto func(F f) -> decltype(???) // what do I put in here?
{
    return [=]()
    {
        return f(someParameter);
    }
}

此代码不起作用,因为我不知道要推断出什么 type 。一种选择是将lambda的主体复制到 decltype 调用中。当然有更好的方法!

This code doesn't work because I don't know what type to deduce. One option might be to copy the body of the lambda into the decltype call. Surely there is a better way!

我想这样做的原因是,我想让编译器更智能地内联或解构lambda的可能性。这种推理有意义吗?如果是这样,为什么?何时返回 std :: function 更好?

My reasoning for wanting to do it this way is that I want to leave open the possibility of the compiler more intelligently inlining or unwrapping the lambdas. Does this reasoning make sense? If so, why, and when is it better simply to return std::function? Could this method ever be slower at compile time?

推荐答案

在C ++ 11中,您无法做到这一点。您可以做一些接近它的事情,但不能这样做。

In C++11 you cannot do this. You can do a few things that are close to it, but not this.

基本上,提取C ++ 11 lambda类型的唯一方法是推断从该类型的实例中获取它,并且您不能在未评估的上下文中命名该类型。因此,函数无法返回其类型取决于lambda类型的类型。 (除非在函数声明之前将lambda与body一起声明,否则在这种情况下没有用)。您可以编写一个作为手动函数对象的仿函数,或使用 std :: bind 为您完成此功能。

Basically, the only way to extract a type of a C++11 lambda is to deduce it from an instance of the type, and you cannot name the type in an unevaluated context. So a function cannot return a type whose type depends on the type of a lambda. (Unless said lambda is declared, with body, prior to the function's declaration, which is not useful in this case). You can write a functor that is a manual function object, or use std::bind which does that for you.

您可以让它评估您也随lambda传递的其他函子,但这很尴尬(尤其是在C ++ 11中,此类函子要么必须键入擦除,要么必须是写成手工的老式函子作为结构)。

You can have it evaluate some other functor you also pass in with the lambda, but that gets awkward (especially in C++11 where such functors either have to type erase, or have to be an old-school functor written "manually" as a struct or class).

一个但是,在C ++ 1y中添加的功能中的以下一项使操作变得容易:

One of the features added in C++1y makes it easy, however:

template<typename F, typename T>
auto func(F f, T t) {
  return [=]() {
    return f(t);
  };
}
int main() {
  auto f = func( [](int x){ std::cout << x << "\n"; }, 7 );
  f();
  f();
}

实时示例

您的编译器可能已经对此功能提供了C ++ 1y支持。

It is possible your compiler already has C++1y support for this feature.

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

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