Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lambda as an argument : std::function or template?

I'm studying c++11 especially interested in lambda.

After some practices, I assumed that lambda closure is an nameless function object.

So I wrote this code.

template <class callable_object>
void lambda_caller( callable_object lambda )
{
    std::cout<< sizeof(lambda) << endl;
    lambda();
}

I know that I can use std::function instead of using template, but I don't want the overhead while typecasting.

But I found one problem reading this question : Why can't I create a vector of lambda in C++11?

The answerer said, "Every lambda has a different type- even if they have the same signature.".

Compilers makes different codes for different classes.

So I think that my compiler will make another version of lambda_caller whenever I make another definition of lambda to pass.

Is there any way to avoid it, except using std::function? Isn't there any generic type for lambda closure?

like image 258
user2020192 Avatar asked Feb 21 '13 09:02

user2020192


1 Answers

You can't avoid it. Lambda is just a class with operator()() overloaded which executes your code. So different code - different classes.

like image 97
ixSci Avatar answered Nov 19 '22 22:11

ixSci