H'H H'H - 1 month ago 6
C++ Question

Possibility of defining one variable with multiple types based on a macro

I am wondering if it is possible to do:

class MyClass
{
public:
MyClass();
...

#if defined USE_TYPE_ONE
static TypeOne myVariable;
#else
static TypeTwo myVariable;
#endif USE_TYPE_ONE
};


The reason is that I have two classes, TypeOne & TypeTwo, with same function variables but different implementations and
I don't want to use macro in every place that myVariable is called.

EDIT

Thanks for prompt comments and answer. I have to mention that MyClass has been used a lot with different classes. That is why I would like to avoid template. Because even using template class with default template argument type, I have to use <> (change many other places) for other places that I use MyClass without need of TypeOne.

Answer

You can use a template as suggested but if you just need to switch between two types according to a condition and you have access to C++11 <type_traits> (otherwise consider updating your compiler), then you could use std::conditional:

#include <type_traits>

constexpr bool USE_TYPE_ONE = true;

struct TypeOne { };
struct TypeTwo { };

class MyClass {
  using Type = std::conditional<USE_TYPE_ONE, TypeOne, TypeTwo>::type;
  static Type myVariable;
};