在编译时选择实现

时间:2013-09-12 19:02:05

标签: c++ design-patterns

假设有人想要创建一个带有两个独立实现的C ++类(比如一个在CPU和GPU上运行),并且希望在编译时发生这种情况。

可以使用哪种设计模式?

4 个答案:

答案 0 :(得分:7)

一本好读的书是:现代C ++设计:应用的通用编程和设计模式,由Andrei Alexandrescu编写。

基本上他说你可以使用基于策略的类来实现你想要的东西(一种策略模式,但是在编译时完成.Bellow是一个简单的例子,显示了这个:

#include <iostream>

using namespace std;

template <typename T>
struct CPU
{
  // Actions that CPU must do (low level)
  static T doStuff() {cout << "CPU" << endl;};
};

template <typename T>
struct GPU
{
  // Actions that GPU must do (low level)
  // Keeping the same signatures with struct CPU will enable the strategy design patterns
  static T doStuff() {cout << "GPU" << endl;};
};

template <typename T, template <class> class LowLevel>
struct Processors : public LowLevel<T>
{
  // Functions that any processor must do
  void process() {
    // do anything and call specific low level
    LowLevel<T>::doStuff();
  };
};

int main()
{
  Processors<int, CPU> cpu;
  Processors<int, GPU> gpu;

  gpu.process();
  cpu.process();
}

答案 1 :(得分:3)

您可以使用简单的模板。 (抱歉粗略的实现,这只是一个例子)

#include <iostream>
struct example
{
    void cpu() { std::cout << "Cpu\n"; }
    void gpu() { std::cout << "Gpu\n"; }

    template<bool useGpu = true>void go() { gpu(); }
};
template<>void example::go<false>() { cpu(); }

int main()
{
    example().go<false>(); //<-- Prints 'Cpu'
    example().go(); // <-- Prints 'Gpu'
}

答案 2 :(得分:3)

最简单的解决方案示例,使用Strategy模式(但是,无论是编译时还是选择运行时都无关紧要):

class BaseStrategy
{
  public:
    virtual void doStuff() = 0;  
};

class Strategy1 : public Base
{
  public:
    void doStuff();
};

class Strategy2 : public Base
{
  public:
    void doStuff();
};

class SomeKindOfAMainClass
{
  public:
    SomeKindOfAMainClass(BaseStrategy* s)
    {
      this->s = s; 
    }
    void doStuff()
    {
      s->doStuff();
    }
  private:
    BaseStrategy* s;
};

然后您只需执行new SomeKindOfAMainClass(new Strategy1())new SomeKindOfAMainClass(new Strategy2())

特征的简单例子:

struct WithStrategy1 {};
struct WithStrategy2 {};

template<typename T>
class SomeKindOfAMainClass;

template<>
class SomeKindOfAMainClass<WithStrategy1>
{
  //use Strategy1 here
};

template<>
class SomeKindOfAMainClass<WithStrategy2>
{
  //use Strategy2 here
};

您只需在程序开头实例化SomeKindOfAMainClass<WithStrategy1>SomeKindOfAMainClass<WithStrategy2>

或者您可以通过#ifdef获得奥马哈提供的解决方案。

答案 3 :(得分:1)

如果你想做出编译时的决定,总会有旧的备用数据库:预处理器。使用#ifdef / #endif块和编译器参数来指定所需的代码。