nbu*_*bis 4 c++ design-patterns
假设有人想要创建一个带有两个独立实现的C++类(比如一个在CPU和GPU上运行),并且希望在编译时发生这种情况.
可以使用什么样的设计模式?
一本好书要读:现代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();
}
Run Code Online (Sandbox Code Playgroud)