How to immediately call C ++ lambda?

The constructor from the inherited class, I require passing a non-trivial object. Similar to this:

MyFoo::MyFoo() : SomeBase( complexstuff )
{
    return;
}

complexstuffhas little to do with MyFoo, so I did not want to miss it.

Instead of writing some kind of temporary 1-off function that returns complexstuff, I used lambda. It took me a few minutes to figure out that I should call a lambda. So now my code is as follows:

MyFoo::MyFoo() : SomeBase(
    []()
    {
        /* blah blah do stuff with complexstuff */
        return complexstuff;
    } () )
{
    return;
}

If you have not noticed this, it is subtle. But after the lambda body I had to put ()in order to tell the compiler to immediately “start” the lambda. It made sense after I realized what I did wrong. Otherwise, without ()calling lambda, gcc says something similar to this:

error: no matching function for call to 'SomeBase(<lambda()>)'

, , ? ++ 11 ++ 14 , , lambda, ? (), ?

+5
4

, - ?

, .

++ 11 ++ 14 , , , ?

, . , (), , ( , , , std::invoke).

, () , .

(), ?

, . , std::invoke , . , () .

+8

. ( , ) - , . , , ( JavaScript).

, SomeBase complexstuff, .


, , Alexandrescu SCOPE_GUARD, :

#include <iostream>

constexpr enum {} invoke{};

template<class Callable>
auto operator+(decltype(invoke) const&, Callable c) -> decltype(c()) {
    return c();
}


int main() {
    invoke + []() {
        std::cout << "called";
    };
}

. DSL, . , .

+4

++ 17 std::invoke. , , , , .

#include <iostream>
#include <functional>

void foo(int i)
{
  std::cout << i << '\n';
}

int main()
{
  foo( std::invoke( []() { return 1; } ) );
}
+3

- complexstuff, -

class MyFoo : public Base {
private:
    static SomeComplexType compute_complex_stuff() {
      SomeComplexType complexstuff;
      /*compute the complexstuff */
      return complexstuff;
    };
public: 
    MyFoo() : Base(compute_complex_stuff()) {};
};

, - ; ; - , (, , - , , , ++ 11 ).

BTW, GCC ( ) .

MyFoo::MyFoo : Base (({
  SomeComplexType complexstuff;
  /*compute the complexstuff */
  return complexstuff;
}) {};
+2

Source: https://habr.com/ru/post/1680581/


All Articles