kaiser soze
kaiser soze

Reputation: 67

How to define variable of unknown type global in if/else sequence?

I have 3 classes:

class A
{
   //
};
class B
{
   //
};
class C
{
   //
};

How can I define variable q with type equal to one of this classes and make it global?

For example in I will define it like this, q won't be global.

if (a == 1) {
    A q;
} else
if (a == 2) {
    B q;
} else
if (a == 3) {
    C q;
} else

Upvotes: 3

Views: 326

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

How can I define variable q with type equal to one of this classes and make it global?

  • I will need only one instance and only once.
  • All of this classes have methods set() and search() that work differently for each of class.

In this case you can consider to use the preprocessor to achieve this via compile time configuration of your program

#define CHOOSE_CLASS 1 // Or use -D option for the compiler in the build system
#if (CHOOSE_CLASS == 1)
A q;
#else
#if (CHOOSE_CLASS == 2)
B q;
#else 
#if (CHOOSE_CLASS == 3)
C q;
#endif
#endif
#endif

Or a template class wrapper to select one of them

class A;
class B;
class C;

enum TypeSelector {
    CLASS_A ,
    CLASS_B ,
    CLASS_C ,
};

template <TypeSelector selection>
struct SelectFinal {
     typedef void FinalType;
};

template<>
SelectFinal<CLASS_A> {
     typedef A FinalType;
};

template<>
SelectFinal<CLASS_B> {
     typedef B FinalType;
};

template<>
SelectFinal<CLASS_C> {
     typedef C FinalType;
};

SelectFinal<CLASS_A>::FinalType q;

If you need to choose the class type at runtime, you want to go for the factory pattern as described in the other answer. Maybe with a slight modification:

class ABCFactory {
public:
    static std::shared_ptr<Base> Create(int index) {
        static std::shared_ptr<Base> theInstance;
        if(!theInstance.get()) {
             switch (index) {
             case 1:
                 theInstance = std::make_shared<A>();
                 break;
             case 2:
                 theInstance = std::make_shared<B>();
                 break;
             case 3:
                 theInstance = std::make_shared<C>();
                 break;
             }
         }
         return theInstance;
     }
 };

Upvotes: 1

szulak
szulak

Reputation: 703

You might want to provide a common base class for A,B,C and make use of factory design pattern.

class A : public Base
{
};

class B : public Base
{
};

class C : public Base
{
};

class ABCFactory
{
public:
 static Base* Create(int index)
 {
    switch (index) 
    {
      case 1:
    return new A;
      case 2:
    return new B;
      case 3:
    return new C;
    };
 }
};

//example usage:
std::unique_ptr<Base> p = ABCFactory::Create(1);

Upvotes: 5

Related Questions