gpt4 book ai didi

c++ - 在编译时选择实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:00:39 25 4
gpt4 key购买 nike

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

为此可以使用什么设计模式?

最佳答案

值得一读的好书是:Modern C++ Design: Generic Programming and Design Patterns Applied,作者是 Andrei Alexandrescu。

基本上他说你可以使用基于策略的类(一种策略模式,但在编译时完成。下面是一个简单的例子来说明这一点)来实现你想要的:

#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();
}

关于c++ - 在编译时选择实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com