dummy() function - What is that supposed to be?

孤街醉人 提交于 2019-12-02 23:26:26

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!