Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose between implementations at compile time

Say one wants to create a C++ class with two separate implementations (say one to run on a CPU and on a GPU) and one wants this to happen at compile time.

What design pattern can be used for this?

like image 965
nbubis Avatar asked Dec 02 '22 18:12

nbubis


1 Answers

A good book to read is: Modern C++ Design: Generic Programming and Design Patterns Applied, written by Andrei Alexandrescu.

Basicly he said that you can implement what you want using policy based class (a kind of strategy pattern, but done at compilation time. Bellow is a simple example showing this:

#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();
}
like image 138
Amadeus Avatar answered Dec 10 '22 12:12

Amadeus