如何在 if/else 序列中定义未知类型的全局变量?

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

我有 3 个 classes:

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

如何定义类型等于 classes 之一的变量 q 并使其成为全局变量?

例如我会这样定义它,q 不会是全局的。

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

您可能希望为 A、B、C 提供一个公共基础 class 并使用工厂设计模式。

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);

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.

在这种情况下,您可以考虑使用预处理器通过程序的编译时配置来实现此目的

#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

或者 class 包装模板 select 其中之一

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;

如果您需要在运行时选择 class 类型,您需要按照其他答案中的描述选择工厂模式。也许稍作修改:

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;
     }
 };