Home > Software engineering >  Is there a way to use regular if/else in header or better options instead preprocessor directives
Is there a way to use regular if/else in header or better options instead preprocessor directives

Time:01-23

class MyMainClass{
//somecodes

// #define XXX 1

#ifdef XXX
    VClass *x = new Class1();
#else
    VClass *x = new Class2();
#endif

//some other codes
}

I have this code in my header file to choose which class i will use for program. I have a globals header file. If i define a var there, can i use it in header without ifdef, define clauses? Like: globals.h:

constexpr bool glb = true;

And use it with regular if/else or something to choose between object instantiations?

CodePudding user response:

The answer is yes; see the code below for an example.

#include <cstdlib>

class VClass
{
public:
   VClass() {/* empty */}
};

class Class1 : public VClass
{
public:
   Class1() {/* empty */}
};

class Class2 : public VClass
{
public:
   Class2() {/* empty */}
};

enum {
   VCLASS_TYPE_CLASS1 = 0,
   VCLASS_TYPE_CLASS2,
   // additional types could be added here in the future
   NUM_VCLASS_TYPES
};

constexpr int glb = VCLASS_TYPE_CLASS1;  // set this per your preference

class MyMainClass
{
public:
   MyMainClass() {/* empty */}
   ~MyMainClass() {delete x;}

private:
   VClass * CreateX() const
   {
      switch(glb)
      {
         case VCLASS_TYPE_CLASS1: return new Class1();
         case VCLASS_TYPE_CLASS2: return new Class2();
         default:                 std::abort();  // bad glb setting!?
      }
   }

   VClass * x = CreateX();
};

int main(int, char **)
{
   MyMainClass mmc;

   return 0;
}
  • Related