Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ lambda returning itself

Tags:

c++

lambda

I wanted to write a lambda that returns itself, so I could call it multiple times on the spot. But it looks like inside of a lambda this refers not to the lambda but to the surrounding object's this, if the lambda is defines inside a member function.

Here's an example:

#include <iostream>

int main(int argc, char* argv[]) {
  int a = 5;
  [&](int b) {
    std::cout << (a + b) << std::endl;
    return *this;
  }(4)(6);
}

Is there a way to do something comparable?

like image 706
SU3 Avatar asked Sep 04 '18 20:09

SU3


1 Answers

With old functor:

int main() {
  int a = 5;
  struct S {
    const S& operator ()(int b) const {
      std::cout << (a + b) << std::endl;
      return *this;
    }
    const int& a;
  };
  S{a}(4)(6);
}

Demo

like image 54
Jarod42 Avatar answered Sep 18 '22 16:09

Jarod42