Question

I want to shorten the following type of lambdas:

[] (SomeVeryLongTemplateType<int, float, char, std::string>, AnotherLongType) {};

Since the only reason for this lambda is to initialize some class std::function<...> member - it doesn't capture anything, it doesn't have argument names, it returns nothing, it does nothing.

If the shortening operation is expressed as a function of the number of arguments in signature, then I want this function to have the complexity O(1).

Is there a way to do that?

Was it helpful?

Solution

Looks like you're looking for an empty lambda which does nothing, so that your std::function object will always be in callable state!

If so, then use this one which can be reused, for any number of parameters:

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

And then use it as:

 std::function<void()>          fun1 = empty_lambda;
 std::function<void(int,int)>   fun2 = empty_lambda;
 std::function<void(whatever)>  fun3 = empty_lambda;

Hope that helps.

OTHER TIPS

in C++14 there will be "generic lambdas" that should simplify long type names in parameters as I understand:

auto lambda = [](auto x, auto y) {return x + y; };

here auto is like Template type

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

You're looking for "polymorphic lambdas". They do not exist (yet), so no.

However, you can make it easier with proper use of typedefs, so you don't have to type the entire thing every single time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top