是否可以在C++中将宏条件与模板参数一起使用

Is it possible to use macro conditions with template arguments in C++?

本文关键字:参数 一起 条件 C++ 是否      更新时间:2023-10-16

像这样:

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
}