Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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.

like image 911
Reflection Avatar asked Jan 09 '23 01:01

Reflection


2 Answers

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;

like image 123
Mark B Avatar answered Jan 24 '23 21:01

Mark B


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
}
like image 32
Jonathan H Avatar answered Jan 24 '23 19:01

Jonathan H