I read this question here on SO and stumbled over the best voted answer, which 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()
.
Let's simplify the declaration a bit by using simpler types and expressions. We'll use int
instead of std::function<void(int)>
, 42
instead of the lambda, and f += 1
instead of f(3)
:
int f{42}, dummy((f += 1, 0));
To make it even more obvious, we can also use braces instead of parentheses for the second initialisation:
int f{42}, dummy{(f += 1, 0)};
This way, it should be clearer. It's a declaration which declares two variables: f
and dummy
. f
is initialised with 42
, and dummy
is initialised with this expression: (f += 1, 0)
. That one's using the comma operator to first evaluate f += 1
, discard the result, and then use the value 0
to initalise dummy
.
Going back to the full (nonsimplified) declaration:
The type of both variables f
and dummy
is std::function<void(int)>
. First f
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 initialise dummy
. Initialising a std::function
with nullptr
results in creating an empty std::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 which f
could be invoked.
where [
dummy
] is declared
In the declaration that you show. Simplified:
T f /* the declarator */, dummy /* the declarator */;
dummy
is just a name of a variable, just like f
. They are both declared in the same declaration.
Could someone explain what that dummy function (or functor) does
I mean obviously in the example it is used to call the function f. But what its actual purpose?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With