如何立即调用C ++ lambda? [英] How to immediately invoke a C++ lambda?
问题描述
我正在继承的类中的构造函数要求传递一个非平凡的对象。类似于此:
A constructor from a class I'm inheriting requires a non-trivial object to be passed in. Similar to this:
MyFoo::MyFoo() : SomeBase( complexstuff )
{
return;
}
复杂物
具有与 MyFoo
几乎没有关系,所以我不想将其传递出去。
The complexstuff
has little to do with MyFoo
, so I didn't want to have to pass it in.
而不是编写某种类型的1-off临时函数返回 complexstuff
我使用了lambda。我花了几分钟才弄清楚我必须调用该lambda。所以我的代码现在看起来像这样:
Instead of writing some kind of 1-off temporary function that returns complexstuff
I used a lambda. What took me a few minutes to figure out is I have to invoke the lambda. So my code now looks like this:
MyFoo::MyFoo() : SomeBase(
[]()
{
/* blah blah do stuff with complexstuff */
return complexstuff;
} () )
{
return;
}
如果您没有抓住它,那就太微妙了。但是在lambda主体之后,我不得不放入()
来告诉编译器立即运行 lambda。在我弄清楚自己做错了什么之后,这才有意义。否则,如果没有()
来调用lambda,gcc会说类似以下内容:
If you didn't catch it, it is subtle. But after the lambda body, I had to put ()
to tell the compiler to immediately "run" the lambda. Which made sense after I figured out what I had done wrong. Otherwise, without the ()
to invoke the lambda, gcc says something similar to this:
error: no matching function for call to 'SomeBase(<lambda()>)'
但是现在我在想-我正确地做到了吗?在C ++ 11或C ++ 14中,是否有更好的方法告诉编译器我希望它立即调用我编写的lambda?还是像我惯常的那样添加空的()
?
But now that has me thinking -- did I do this correctly? Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written? Or is appending an empty ()
like I did the usual way to do this?
推荐答案
但是现在我在想-我正确地做到了吗?
But now that has me thinking -- did I do this correctly?
是
在C ++ 11或C ++ 14中是否有更好的方法告诉编译器我希望它立即生效调用我编写的lambda吗?
Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written?
我不知道。 Lambda也是一个函数对象,因此您需要要有一个()
来调用它,没有办法解决(除了当然,某些函数会调用lambda,例如 std :: invoke
)。
Not that I know of. A lambda is also just a function object, so you need to have a ()
to call it, there is no way around it (except of course some function that invokes the lambda like std::invoke
).
如果需要,可以删除()
,因为您的lambda不接受任何参数。
If you want you can drop the ()
after the capture list, because your lambda doesn't take any parameters.
或者像我惯常的那样添加空的
()
这是
是的,这是最短的方法。如前所述, std :: invoke
也可以代替,但需要更多的输入。我想说直接使用()
进行调用是常见的方法。
Yes, it is the shortest way. As said before, std::invoke
would also work instead, but it requires more typing. I would say a direct call with ()
is the usual way it is done.
这篇关于如何立即调用C ++ lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!