【问题标题】:how to send a callback to a class如何向类发送回调
【发布时间】:2017-03-23 22:30:34
【问题描述】:

我有一个类:market simulator,它有一个方法 send_order(int qty, string symbol, double price),由我的 xyz_strategy 类调用,这是一个正在测试的交易策略。当market_simulator 收到订单时,它会检查市场价格并决定是否可以执行订单。它的标题是这样的:

class market_simulator {
    std::vector<order> orders;
    static std::shared_ptr<market_simulator> instance;
    std::map<std::string,std::shared_ptr<instrument> > instruments;
    ...
public:
    static std::shared_ptr<market_simulator> market();
    ... 
    void send_order(int qty, std::string symbol, double price);
};

问题是我需要一种方法让market simulator 将填充报告发回给发件人。

我的第一次尝试是将指向类的指针发送到市场模拟器。但是市场模拟器必须包含“xyz_strategy”(和其他策略),然后它也可以访问它的所有方法。

我的第二次尝试是创建一个虚拟超类order_sender,它有一个名为fill_report(int qty, string symbol, double price) 的方法。现在市场模拟器只知道order_sender,只能调用它的一种方法。但是现在策略有太多的超类需要实现。

如何在 c++ 中实现一个指向函数的指针,这样market_simulator 只知道这个函数并在它执行时调用它?

编辑:发送指针的函数类似于:

 void on_execution(int quantity, std::string symbol, double price);

【问题讨论】:

    标签: c++ architecture


    【解决方案1】:

    callback 函数至少有两个选项,1) 函数指针和 2) 函数对象(函子)。

    函数指针

    使用指向函数的指针时,使用typedef 通常会使程序更具可读性:

    typedef void (*Function_Pointer)(const std::string&);
    

    然后您可以将函数指针传递给另一个函数:

    void Logger(Function_Pointer output_function)
    {
      output_function("Hello");
    }
    

    函数对象

    函数对象是重载operator()classstruct

    struct Function_Object
    {
      void operator()(const std::string& text)
      {
        std::cout << text << "\n";
      }
    };
    

    您可以像传递任何其他对象一样传递函数对象:

    void Logger_2(Function_Object& functor)
    {
      functor("Hello");
    }
    

    函数对象的一个​​很好的属性是,您可以为一系列回调定义抽象函数对象。

    【讨论】:

      【解决方案2】:

      您可以使用函数指针或 lambda 表达式来委托所需的回调逻辑。

      类似的东西;

      void send_order(int qty, std::string symbol, double price, void (*callback));
      // ...
      send_order(1, "symbol", 1, []() -> void { // callback logic } )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2015-07-16
        • 2011-09-11
        • 2017-07-18
        • 2020-05-06
        相关资源
        最近更新 更多