简体   繁体   中英

Template in C++ with raw type

In Java, we can do something like this:

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++?

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>(); . 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>()希望我的回答可以对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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