简体   繁体   中英

pass lambda to constructor of member variable

Consider the following classes,

template <class L>
class A {
public:
  A(L l) : _l(l) {}
private:
  L _l;
};

class B {
public:
  B(int x) : _x(x), _a([this]() { return _x; }) {}
private:
  int _x;
  A<???> _a;
};

I am not sure how to specify the type at ??? . std:: function<int()> works, but to my knowledge, this implies virtual function calls (of course, this does not have to be bad, but it would be interesting how to do this properly).

Rather than a lambda, you can use a function object that's roughly equivalent.

template <class L>
class A {
public:
  A(L l) : _l(l) {}
private:
  L _l;
};

class B {
  struct GetX
  {
    int operator()() const { return _b->_x; }
    B * _b;
  };
public:
  B(int x) : _x(x), _a(GetX{ this }) {}
private:
  int _x;
  A<GetX> _a;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM