使用lambda作为参数:std :: function或template? [英] Using lambda as an argument : std::function or template?
问题描述
我在学习c ++ 11,特别是对lambda感兴趣。
I'm studying c++11 especially interested in lambda.
在一些实践后,我假设lambda闭包是一个无名的函数对象。
After some practices, I assumed that lambda closure is an nameless function object.
所以我写了这段代码。
template <class callable_object>
void lambda_caller( callable_object lambda )
{
std::cout<< sizeof(lambda) << endl;
lambda();
}
我知道我可以使用 std :: function
I know that I can use std::function
instead of using template, but I don't want the overhead while typecasting.
但我发现一个问题,阅读这个问题:为什么我不能在C ++ 11中创建一个lambda的向量?
But I found one problem reading this question : Why can't I create a vector of lambda in C++11?
回答者说,每个lambda都有不同的类型,即使他们有相同的签名。
The answerer said, "Every lambda has a different type- even if they have the same signature.".
编译器为不同的类创建不同的代码。
Compilers makes different codes for different classes.
所以我认为我的编译器会创建另一个版本 lambda_caller
每当我对另一个lambda定义传递。
So I think that my compiler will make another version of lambda_caller
whenever I make another definition of lambda to pass.
有任何方法可以避免它,除非使用 std :: function
?是否有任何通用类型的lambda闭包?
Is there any way to avoid it, except using std::function
? Isn't there any generic type for lambda closure?
推荐答案
你不能避免它。 Lambda只是一个带有operator()()重载的类,它执行你的代码。所以不同的代码 - 不同的类。
You can't avoid it. Lambda is just a class with operator()() overloaded which executes your code. So different code - different classes.
这篇关于使用lambda作为参数:std :: function或template?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!