如何从if语句中获取类模板的实例? (C ++) [英] How to get instance of class template out of the if statement? (C++)

查看:89
本文介绍了如何从if语句中获取类模板的实例? (C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含成员pData的类模板,该成员是任意类型TAxB数组.

Suppose I have a class template which have a member pData, which is an AxB array of arbitary type T.

template <class T> class X{ 
public:
    int A;
    int B;
    T** pData;
    X(int a,int b);
    ~X();        
    void print(); //function which prints pData to screen

};  
template<class T>X<T>::X(int a, int b){ //constructor
    A = a;
    B = b;
    pData = new T*[A];
    for(int i=0;i<A;i++)
        pData[i]= new T[B];
    //Fill pData with something of type T
}
int main(){
    //...
    std::cout<<"Give the primitive type of the array"<<std::endl;
    std::cin>>type;
    if(type=="int"){
        X<int> XArray(a,b);
    } else if(type=="char"){
        X<char> Xarray(a,b);
    } else {
        std::cout<<"Not a valid primitive type!";
    } // can be many more if statements.
    Xarray.print() //this doesn't work, as Xarray is out of scope.
}

由于实例Xarray是在if语句内部构造的,因此我无法在其他任何地方使用它.我试图在if语句之前创建一个指针,但是由于此时指针的类型未知,所以我没有成功.

As the instance Xarray is constructed inside of an if statement, I cannot use it anywhere else. I tried to make a pointer before the if statements but as the type of the pointer is unknown at that point, I did not succeed.

解决此类问题的正确方法是什么?

What would be a proper way of dealing with this kind of a problem?

推荐答案

C ++是一种静态类型的语言,这意味着您必须在编译时知道对象的类型.在这种情况下,您将基于用户输入构造对象的类型,因此无法在运行时知道类型.

C++ is a statically typed language, meaning that you must know the type of objects at compile time. In this case you are basing the type of the object constructed on user input, so it's not possible to know the type at runtime.

解决此问题的最常用方法是使用动态多态性,其中使用后期绑定通过通用接口调用函数.我们使用虚拟函数在C ++中完成此操作.例如:

The most common way to address this issue is to use dynamic polymorphism in which functions are invoked via a common interface using late binding. We accomplish this in C++ using virtual functions. For example:

struct IPrintable {
   virtual void print() = 0;
};

template<class T>
class X : public IPrintable {
  // Same code as you showed above.
};

int main() {
  std::cout<<"Give the primitive type of the array"<<std::endl;
  std::cin>>type;

  std::unique_ptr<IPrintable> XArray;

  if(type=="int"){
      XArray.reset(new X<int>(a,b));
  } else if(type=="char"){
      XArray.reset(new X<char>(a,b));
  } else {
      std::cout<<"Not a valid primitive type!";
  } // can be many more if statements.

  Xarray->print() // this works now!
}

这解决了超出范围的问题,并允许您使用XArray变量的动态类型进行打印.虚拟功能是使之成为可能的秘密所在.

This solves the out of scope issue and allows you to print using the dynamic type of the XArray variable. Virtual functions are the secret sauce that make this possible.

这篇关于如何从if语句中获取类模板的实例? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆