Something like:
template<bool HOLD_MANUFACTURER>
class Computer {
int memory;
int storage;
#if HOLD_MANUFACTURER
char *manufacturer;
#endif
};
I need this to create two variations of the almost-same class, when one variation is a lighter one for performance reasons. I don't want to use a separate class that will wrap the lighter one.
If yes, is it possible to any type (not just bool from the sample code above)? Maybe primitive types only? What about enums?
This code don't work for me, but I hope that I've just missed some little thing.
You can creatively use the empty base optimization in a policy approach to achieve almost what you want:
struct NO_MANUFACTURER {};
struct HOLD_MANUFACTURER { char *manufacturer; };
template <typename ManufacturerPolicy>
class Computer : public ManufacturerPolicy
{
int memory;
int storage;
}
Then instantiate as Computer<HOLD_MANUFACTURER> computer_with_manufacturer;
Not possible, but you can use template specialization and inheritance:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With