So yesterday I read this question here on SO and stumbled over the best voted answer, wich used code like this to call a lambda recursively
std::function<void(int)>
f {[&f](int i){
// do something
}},
dummy((f(3), nullptr));
I wondered what the dummy(...)
part was about so I did some research but couldn't find anything about it. In the code snippet provided in the answer there was the <utility>
header used so I guess that thing must be declared somewhere in there, but I still couldn't find anything about it.
Could someone explain what that dummy
function (or functor) does, where it is declared and what it is usually used for?
I mean obviously in the example it is used to call the function f. But what its actual purpose?
NOTE: I know that question is a little broad, but since I couldn't find any information about it I could not focus the question onto one specif problem. Also I hope that an answer to my questions will help others finding information about the mysterious dummy()
.
In the declaration that you show. Simplified:
dummy
is just a name of a variable, just likef
. They are both declared in the same declaration.That is the actual purpose. The only reason it is declared, is so that
f
could be called within the same declaration, as was desired in the linked question. The solution is silly, but so is perhaps the desire.Let's simplify the declaration a bit by using simpler types and expressions. We'll use
int
instead ofstd::function<void(int)>
,42
instead of the lambda, andf += 1
instead off(3)
:To make it even more obvious, we can also use braces instead of parentheses for the second initialisation:
This way, it should be clearer. It's a declaration which declares two variables:
f
anddummy
.f
is initialised with42
, anddummy
is initialised with this expression:(f += 1, 0)
. That one's using the comma operator to first evaluatef += 1
, discard the result, and then use the value0
to initalisedummy
.Going back to the full (nonsimplified) declaration:
The type of both variables
f
anddummy
isstd::function<void(int)>
. Firstf
is initialised with a lambda. Then,dummy
is initialised using a comma expression. The left-hand side of that expression,f(3)
, is evaluated and forgotten. The right-hand side,nullptr
, is then used to initialisedummy
. Initialising astd::function
withnullptr
results in creating an emptystd::function
object (the same as a default-constructed one).The whole purpose of
dummy
is to introduce some extra context on the same line (= in the same declaration) in whichf
could be invoked.