H'H H'H - 1 year ago 63
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

#if defined USE_TYPE_ONE
static TypeOne myVariable;
static TypeTwo myVariable;

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.


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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download