c++ - 如何在 C++ 中使用 std::function 实现策略模式

标签 c++ pointers c++11 strategy-pattern std-function

我正在讨论在 C++ 中实现策略模式的最佳方式。到目前为止,我一直使用标准方式,其中上下文有一个指向基本策略类的指针,如下所示:

 class AbstractStrategy{
 public:
     virtual void exec() = 0;
 }
 class ConcreteStrategyA{
 public:
     void exec();
 }
 class ConcreteStrategyB{
 public:
     void exec();
 }

 class Context{
 public:
     Context(AbstractStrategy* strategy):strategy_(strategy){}
     ~Context(){
          delete strategy;
       }
      void run(){
           strategy->exec();
      }
 private:
     AbstractStrategy* strategy_;

由于指向对象的指针会导致不良行为,因此我一直在寻找一种更安全的方法来实现此模式,然后我找到了 this question其中 std::function 被提议作为处理这种模式的更好方法。

有人可以更好地解释 std::function 是如何工作的,也许可以举一个策略模式的例子吗?

最佳答案

请注意,单一方法对象与函数同构,而策略只是单一方法对象。

所以基本上,你摆脱了所有的类,你只使用 std::function<void()>相反:

class Context {
public:
    template<typename F>
    explicit Context(F strategy) : strategy(std::move(strategy)) { }

    void run() { strategy(); }

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

然后您可以将任何可调用对象传递给 Context 的构造函数:

Context ctx([] { std::cout << "Hello, world!\n"; });
ctx.run();

关于c++ - 如何在 C++ 中使用 std::function 实现策略模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29031782/

相关文章:

c - 关于C中的函数指针?

c - 为结构中的数组分配内存(在 C 中)

c++ - 外部进程与线程和数据处理

c++ - 分配默认值 std::function

c++ - 在函数中操作尚未维数的数组

c - 如何从 c 中的字符串数组访问单个字符?

c++ - “send to”如何管理输入参数? ( Windows )

c++ - 跨编译器的诊断不一致,以缩小非类型模板参数中的转换范围

c++ - 将结构成员写入二进制文件并在 C++ 中使用 fstream 读取它们

c++ - 连续使用 cin cout 和 gets 时,C 指令正在重新排序