是否可以在C++中将宏条件与模板参数一起使用
Is it possible to use macro conditions with template arguments in C++?
像这样:
template<bool HOLD_MANUFACTURER>
class Computer {
int memory;
int storage;
#if HOLD_MANUFACTURER
char *manufacturer;
#endif
};
我需要它来创建几乎相同类的两个变体,当一个变体出于性能原因而更轻时。我不想使用一个单独的类来包装较轻的类。
如果是,是否可以使用任何类型(不仅仅是上面示例代码中的布尔值)?也许只有基元类型?枚举呢?
这段代码对我不起作用,但我希望我只是错过了一些小东西。
您可以在策略方法中创造性地使用空基优化来实现几乎您想要的:
struct NO_MANUFACTURER {};
struct HOLD_MANUFACTURER { char *manufacturer; };
template <typename ManufacturerPolicy>
class Computer : public ManufacturerPolicy
{
int memory;
int storage;
}
然后实例化为Computer<HOLD_MANUFACTURER> computer_with_manufacturer;
不可能,但您可以使用模板专用化和继承:
template <bool HoldManufacturer>
class ComputerAdditions
{};
template <>
class ComputerAdditions<true>
{
protected:
char *manufacturer;
public:
// Methods using this additional member
};
template <bool HoldManufacturer = false>
class Computer
: public ComputerAdditions<HoldManufacturer>
{
int memory;
int storage;
public:
// Methods of Computer
}
相关文章:
- 如何将enable-if与模板参数和参数包一起使用
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 概念可以与模板模板参数一起使用吗?
- 为什么当我尝试将priority_queue与参数一起使用作为指向结构的指针时会弹出错误
- 标准::原子::compare_exchange与两个memory_order参数一起使用的真实示例
- 如何在 C++ 中将 typedef 与类初始值设定项参数一起使用?
- 我可以将"token pasting operator"与"const"模板参数一起使用吗?
- 哪个强制转换应与模板类参数一起使用,dynamic_cast或reinterpet_cast?
- 将 boost::function 与指向派生类的共享指针的参数一起使用
- 如何将 #ifndef 与宏参数一起使用
- 如何将初始值设定项与右值引用参数一起使用 // 为什么不能使用另一个 C 样式数组变量初始化 C 样式数组
- 将模板类与引用非类型模板参数一起使用时出现链接器错误
- 如何将QDebug()与QT中的两个参数一起使用
- 将函数与指针参数一起使用作为另一个函数的参数
- 是否可以在C++中将宏条件与模板参数一起使用
- 提升program_options解析选项和参数一起
- 在C++中,如何仅将长选项与必需参数一起使用
- 当通过引用指针将函数与参数一起使用时会发生什么
- 将typedef与构造函数参数一起使用
- 将函数指针上的参数与默认值参数一起丢弃是否有效