c++ - 使用接口(interface)类作为另一个类中的成员类型

标签 c++ visual-c++ design-patterns

我正在尝试设计一段需要使用算法的代码。该算法将来应该很容易被其他人替换。所以在我的 LargeClass 中必须有一种方法来调用特定的算法。

我在下面提供了一些示例代码。我的想法是创建一个接口(interface)类 IAlgorithm,这样您就必须自己提供一个实现。我认为您可以在 LargeClass 的构造函数中将它初始化为您想要的派生类。但是下面的代码在 VS2015 中无法编译,因为 IAlgorithm: cannot instantiate abstract class

我的问题:我应该如何设计才能得到我想要的结果?

提前致谢!

算法.h

class IAlgorithm
{
protected:
    virtual int Algorithm(int, int) = 0;
};

class algo1 : public IAlgorithm
{
public:
    virtual int Algorithm(int, int);
};

class algo2 : public IAlgorithm
{
public:
    virtual int Algorithm(int, int);
};

算法.cpp

#include "Algorithm.h"

int algo1::Algorithm(const int a, const int b)
{
    // Do something
}

int algo2::Algorithm(const int a, const int b)
{
    // Do something
}

源.cpp

#include "Algorithm.h"

class LargeClass
{

private:
    IAlgorithm algo;
};

int main()
{


}

最佳答案

对此我的第一个想法是,为什么要使用如此原始的界面?

好的,我们有一个要求,即某些进程需要将算法发送到其中。这个算法必须是多态的,它必须接受两个整数并返回一个整数。

一切都很好。标准库中已经有一个用于此的构造。它调用 std::function。这是任何具有兼容接口(interface)的函数对象的包装器。

例子:

#include <functional>
#include <iostream>

class LargeClass
{
  public:

  using algorithm_type = std::function<int(int,int)>;

  LargeClass(algorithm_type algo)
  : _algo(std::move(algo))
  {}

  int apply(int x, int y) {
    return _algo(x,y);
  }

private:
    algorithm_type _algo;
};

int test(LargeClass&& lc) {
  return lc.apply(5,5);
}

int divide(int x, int y) { return x / y; }

int main()
{
  // use a lambda
  std::cout << test(LargeClass{ [](auto x,auto y){ return x + y; } });

  // use a function object
  std::cout << test(LargeClass{ std::plus<>() } );

  // use a free function
  std::cout << test(LargeClass{ divide } );

  // use a function object

  struct foo_type {
    int operator()(int x, int y) const {
      return x * 2 + y;
    }
  } foo;
  std::cout << test(LargeClass{ foo_type() } );
  std::cout << test(LargeClass{ foo } );

}

关于c++ - 使用接口(interface)类作为另一个类中的成员类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38290427/

相关文章:

c++ - 使用现有类设计实现功能的问题

c++将数组直接传递给函数

c++ - 来自 dll 的运行函数的访问冲突

c++ - MSBuild 构建后步骤

windows - 为 Win32 编译 OpenSSL 时出错

asp.net - DTO 模式策略 - 每个实体有多个 DTO 还是只有一个?

java - 从基类设置派生类成员

c++ - 默认模板参数中的 lambda 是否被视为直接上下文的一部分?

visual-studio - IntelliSense 解析时是否定义了宏?

design-patterns - 为什么是代理模式是结构模式,为什么是状态模式是行为模式?