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

Template in C++ with raw type

本文关键字:C++ 模板 类型 原始      更新时间:2023-10-16

在Java中,我们可以做这样的事情:

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

相对

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

我们怎么能在C++中找到相似的东西?

与您所写的不完全一样。

你可以做以下事情之一,这取决于你实际想要实现的目标:

  • 在C++11中,可以使用auto自动适应类型:auto = new ArrayList<String>();。这不会给你多态性,但它确实节省了你在左手边键入类型名的时间
  • 如果想要多态性,可以向类层次结构中添加一个级别,并使左侧指向父类

下面是第二种方法的示例:

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

然后,你可以在代码中说:

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

等等

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