简体   繁体   English

具有原始类型的C ++模板

[英]Template in C++ with raw type

In Java, we can do something like this: 在Java中,我们可以执行以下操作:

ArrayList arrayList = new ArrayList<String>(); 
// Notice that String is not mentioned in the first declaration of array

AS OPPOSED TO 相反

ArrayList<String> arrayList = new ArrayList<String>(); 

How can we something in similar in C++? 我们如何在C ++中进行类似的处理?

Not in exactly the way you've written. 并非完全按照您编写的方式进行。

What you can do is one of the following, depending on what you're actually trying to accomplish: 根据实际要完成的操作,您可以执行以下操作之一:

  • In C++11, you can use auto to automatically adapt to the type: auto = new ArrayList<String>(); 在C ++ 11中,可以使用auto自动适应以下类型: auto = new ArrayList<String>(); . This doesn't give you polymorphism, but it does save you typing the typename on the left hand side. 这不会给您多态性,但是可以节省您在左侧键入类型名的时间。
  • If you want polymorphism, you can add a level to your class hierarchy, and make the left-hand side point to a parent class. 如果需要多态,可以将一个级别添加到类层次结构中,并使左侧指向父类。

Here's an example of the second approach: 这是第二种方法的示例:

class IArrayList   // define a pure virtual ArrayList interface
{
     // put your interface pure virtual method declarations here
};

template <typename T>
class ArrayList : public IArrayList
{
     // put your concrete implementation here
};

Then, you could say in your code: 然后,您可以在代码中说:

IArrayList* arrayList1 = new ArrayList<string>();
IArrayList* arrayList2 = new ArrayList<double>();

...and so on. ...等等。

在c ++中,不能使用vector array = new vector<string>() ,但是在c ++ 11中,可以使用auto关键字: auto p = new vector<string>() ,它与vector<string> *p = new vector<string>()相同vector<string> *p = new vector<string>()希望我的回答可以对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM