有没有办法在声明中缩短C++ 11 lambda签名?

aby*_*s.7 21 c++ lambda syntactic-sugar c++11

我想缩短以下类型的lambdas:

[] (SomeVeryLongTemplateType<int, float, char, std::string>, AnotherLongType) {};
Run Code Online (Sandbox Code Playgroud)

因为这个lambda的唯一原因是初始化一些类std::function<...>成员 - 它不捕获任何东西,它没有参数名称,它什么都不返回,它什么都不做.

如果缩短操作表示为签名中参数数量的函数,那么我希望此函数具有复杂度O(1).

有没有办法做到这一点?

Naw*_*waz 33

看起来你正在寻找一个什么都不做的空lambda,这样你的std::function对象总是处于可调用的状态!

如果是这样,那么对于任意数量的参数,使用可以重复使用的那个:

static const struct empty_lambda_t //static and const applies to the object!
{
      template<typename ...T>
      void operator()(T && ... ) const {} //does nothing

}empty_lambda {}; //declare an object which is static and const
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

 std::function<void()>          fun1 = empty_lambda;
 std::function<void(int,int)>   fun2 = empty_lambda;
 std::function<void(whatever)>  fun3 = empty_lambda;
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

  • 挑剔:"无论什么"必须是"无效(无论如何)".它除了`void`之外不能有返回类型 (2认同)

fen*_*fen 11

在C++ 14中,将会有"通用lambdas",它应该简化参数中的长类型名称,如我所知:

auto lambda = [](auto x, auto y) {return x + y; };
Run Code Online (Sandbox Code Playgroud)

这里auto就像模板类型

http://en.wikipedia.org/wiki/C%2B%2B14#Generic_lambdas