类中的 C++ 注入函数

c++ inject function in class

本文关键字:注入 函数 C++      更新时间:2023-10-16

我有这个基类:

class Task {
private:
    bool enabled;
    void (*foo)();
public:
    virtual void init(int period) { enabled = true; }
    virtual void tick() = 0;
    void high(void (*f)()) { foo = f; }
    void callFoo() { foo(); }
    bool isEnabled() { return enabled; }
};

以及使用此方法实现Task的类:

LedTask::LedTask(int pin, Context* pContext) {
    this->pin = pin;
    this->pContext = pContext;
}
void LedTask::init(int period) {
    Task::init(period);
    this->led = new Led(pin);
}
void LedTask::tick() {
    Task::callFoo();

}

main()

Task* t3 = new LedTask(LED_PIN, c);
t3->init(50);
t3->high([]{Serial.println("ok");});

这有效,但我想知道如何访问t3实例的私人(和公共)成员; 像这样:

t3->high([]{ led->switchOn(); });

简而言之,我想在类中注入一个函数并在其中使用它的类成员。

正如我在评论中提到的,我想你的LedTask类继承自Task.

因此,您应该将函数指针放在 Task 类中,以支持必须在继承类中实现的纯virtual函数:

class Task {
private:
    bool enabled;
protected: 
    virtual void foo() = 0; // <<<<<<<<<<<<<<<<<<<<<<<<<<
public:
    virtual void init(int period) { enabled = true; }
    virtual void tick() = 0;
    // void high(void (*f)()) { foo = f; } << not needed
    void callFoo() { foo(); }
    bool isEnabled() { return enabled; }
};

然后在LedTask的第二步中,基于 std::function 构造函数参数实现foo

class LedTask : public Task {
public:
    LedTask(uint8_t pin, Context* pContext , std::function<void()> f) 
    : pin_(pin), pContext_(pContext), f_(f) {
    }
private:
    void foo() {
        f_();
    }
    uint8_t pin_;
    Context* pContext_;
    std::function<void()> f_;
};

好吧,从您的评论中听起来您需要Led对象作为注入函数的参数。

init() 中创建的Led的成员指针应传递给注入的函数。

您可以使用类似的东西

    std::function<void(Led&)> f_;

    void(*f_)(Led&);

传递该参数是在实现中完成的,如上所述:

    void foo() {
        f_(*led);
    }