如何声明一个接受lambda的函数?
我在互联网上阅读了很多教程,解释了如何使用标准库(例如 std :: find
)来使用lambdas,而且都非常有趣,我找不到任何解释我如何使用lambda为我自己的函数。
I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find
), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions.
例如:
int main()
{
int test = 5;
LambdaTest([&](int a) { test += a; });
return EXIT_SUCCESS;
}
如何声明 LambdaTest
?它的第一个参数的类型是什么?然后,我如何调用传递给它的匿名函数 - 例如 - 10作为参数?
How should I declare LambdaTest
? What's the type of its first argument? And then, how can I call the anonymous function passing to it - for example - "10" as its argument?
除了lambdas,你可能还想接受函数指针和函数对象,你可能想使用模板来接受任何带有 operator()
的参数。这是std函数找到做的。它看起来像这样:
Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator()
. This is what the std-functions like find do. It would look like this:
template<typename Func>
void LambdaTest(Func f) {
f(10);
}
请注意,此定义不使用任何c ++ 0x功能,因此它完全向后兼容。这只是使用lambda表达式的函数调用,它是c ++ 0x特定的。
Note that this definition doesn't use any c++0x features, so it's completely backwards-compatible. It's only the call to the function using lambda expressions that's c++0x-specific.