在c++中实现回调的最好方法是什么?

What would be the best way to implement callback in C++

本文关键字:方法 是什么 c++ 实现 回调      更新时间:2023-10-16

我对学习别人如何设计他们的软件很感兴趣。我在不同的项目中使用了不同的解决方案,但我觉得我可以做得更好。我的实现涉及到委托和观察者的使用,但是今天我忍不住问你,你会怎么写它。

让我们假设我们有以下内容:

class Sensor
{
  ...
  public:
    void sensorTriggered();
};
Class Device
{
  ...
  public:
    void notifyChangesFromHardware(unsigned int inNotificationInfo);
  protected:
    Sensor *fireAlarm_;
};
int main()
{
  Device someDevice;
  return 0;
}

如果你想调用"Device::notifyChangesFromHardware"你会怎么设计呢?从传感器对象(fireAlarm_)?

谢谢

我会使用函数指针或函数对象:

struct Notifier_Base
{
  virtual void notify(void) = 0;
};
class Sensor
{
  std::vector<Notifier_Base *> notifiers;
  void publish(void)
  {
    std::vector<Notifier_Base *>::iterator iter;
    for (iter =  notifiers.begin();
         iter != notifiers.end();
         ++iter)
    {
      (*iter)->notify();
    }
};

请参阅设计模式:发布者/使用者、发布者/订阅者。

我会看看Boost Signals也像Piotr s建议。此外,我使用的一个简单模式在您的例子中看起来像这样:

template<class NotifyDelegate>
class Sensor
{
  ...
  public:
    // assumes you only have one notify delegate
    Sensor( NotifyDelegate &nd ) : nd_(nd)
    {
    }
    void sensorTriggered()
    {
        unsigned int notifyInfo = 99;
        nd_.notifyChangesFromHardware( notifyInfo );
    }

  private:
    NotifyDelegate &nd_;
};

Class Device
{
  ...
  public:
    void notifyChangesFromHardware(unsigned int inNotificationInfo);
};
int main()
{
  Device someDevice;
  Sensor<Device> someSensor(someDevice);
  someSensor.sensorTriggered();
  return 0;
}

也看看Observer Pattern