gpt4 book ai didi

c++ - 如何在成员模板函数中为不同类型选择代码路径

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

我有一个基于运行时返回特定设备的类。

struct ComponentDc;
struct ComponentIc;

typedef Device<ComponentDc> DevComponentDc;
typedef Device<ComponentIc> DevComponentIc;

template<class Component>
class Device{
Device<Component>* getDevice() { return this; }
void exec() { }
};

exec() 中,如果组件类型是 ComponentDc 我想打印“Hello”,如果是 ComponentIc 我想打印 world .此外,只有这两种类型可以用来创 build 备。

我该怎么做?

最佳答案

你有两种经典的可能性。

首先,使用两个全局函数重载,一个用于ComponentDc,一个用于ComponentIc:

void globalExec(ComponentDc) { std::cout << "Hello"; }
void globalExec(ComponentIc) { std::cout << "World"; }

void Device<Component>::exec() { globalExec(Component); }

其次,使用 traits-class:没有字段和不同 typedef 的纯模板类,只有静态函数作为方法。此类针对不同的可能参数类型具有自己的特化。

template<Component> class DeviceTraits {};

template<> class DeviceTraits<ComponentDc> {
static std::string getMessage() { return "Hello"; }
};

template<> class DeviceTraits<ComponentIc> {
static std::string getMessage() { return "World"; }
};

void Device<Component>::exec() {
std::cout << DeviceTraits<Component>::getMessage();
}

使用 traits 类的优点是您不必用多个函数破坏您的全局命名空间。

关于部分特化 Device 类本身——这并不总是可能的,而且将任何特定于模板参数的代码移动到 traits 类中被认为更方便。

这是STL中使用的经典方法。或者,您可以使用 boost::enable_ifstd::enable_if(对于最新的编译器)。

关于c++ - 如何在成员模板函数中为不同类型选择代码路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15494531/

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