cc_
cc_

Reputation: 19

c++11 accessing "this" from lambda passed to constructor

Is there an elegant way of accessing "this" in a lambda that is passed to the constructor?

This works, but is not elegant!

#include <iostream>
#include <functional>

class CbClass {
 public:
  CbClass(int x, std::function< void() > cb) : x_(x),cb_(cb) {}
  int x_;
  std::function< void() > cb_;
  void call() { if (cb_) cb_(); };
};

int main() {

  CbClass* p(nullptr);
  CbClass** pp(&p);
  CbClass cb( 13 , [pp] () { std::cout << (*pp)->x_ << std::endl; } );
  p = &cb;

  cb.call();

}

Upvotes: 1

Views: 79

Answers (2)

Khouri Giordano
Khouri Giordano

Reputation: 1461

You would pass this to the lambda in the call function:

#include <iostream>
#include <functional>

class CbClass {
public:
    CbClass(int x, std::function< void( CbClass * ) > cb) : x_(x),cb_(cb) {}
    int x_;
    std::function< void( CbClass * ) > cb_;
    void call() { if (cb_) cb_( this ); };
};

int main() {
   CbClass cb( 13 , [] ( CbClass *p ) { std::cout << p->x_ << std::endl; } );
   cb.call();
}

Upvotes: 3

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

You cannot access this. You can access a random captured CbClass object, which the caller arranges to be the object under construction. You don't need to manipulate any pointers for that.

int main() {
  CbClass cb(13, [&cb]() { std::cout << cb.x_ << std::endl; });
  cb.call();
}

Upvotes: 2

Related Questions