首页 > 解决方案 > Can an anonymous lambda function be bound to an object to allow the code in the lambda to access the object's members?

问题描述

I want to allow a lambda function to access members of an object. There are 2 classes involved here:

The class I want to access

class D {
public:
  void doIt() {};
};

An initializer class for management

template<typename T>
class I {
public:
    I(std::function<void ()> f) {
      someManager->register(this);
      _func = f;
    }

    void run() {
        T* t = new T();
        auto fn = std::bind(t, _func);
        fn();
    }

private:
    std::function<void ()> _func;
};

static I<D> _init_([]() {
    doIt();
});

Then in someManager I'd call: i->run(). However, the call to doIt() is not accepted. What must be changed to make this compile and work?

标签: c++

解决方案


带有修复的工作版本:

class D {
public:
  void doIt() {};
};

template<typename T>
class I {
public:
    I(std::function<void(D*)> f) {
      _func = f;
    }

    void run() {
        T* t = new T();
        auto fn = std::bind(_func, t);
        fn();
        // Alternatively.
        _func(t);
    }

private:
    std::function<void(D*)> _func;
};

I<D> _init_([](D* p) {
    p->doIt();
});

int main() {
    _init_.run();
}

而不是std::function<void(D*)>你也可以使用void(*)(D*),因为 lambda 表达式[](D* p) { p->doIt();}不捕获任何东西,因此它可以转换为普通函数指针void(*)(D*)

代码也不需要D在堆上分配,一个自动对象就足够了。例如:

void run() {
    T t;
    _func(&t);
}

推荐阅读