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

前端 未结 2 1509
清歌不尽
清歌不尽 2021-02-03 20:23

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
           


        
相关标签:
2条回答
  • 2021-02-03 20:41

    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.

    0 讨论(0)
  • 2021-02-03 20:58

    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.

    0 讨论(0)
提交回复
热议问题