带有原始类型的C++模板
Template in C++ with raw type
在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>()
相同。希望我的答案能对您有所帮助。
相关文章:
- .cpp和.h文件中的模板专用化声明
- C++模板来检查友元函数的存在
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何在c++中为模板函数实例创建快捷方式
- 使用C++中的模板和运算符重载执行矩阵运算
- 有人能分解一下这个c++模板的语法吗
- 如何在c++17中制作一个模板包装器/装饰器
- 模板化建造师专业化
- 调用专用模板时出错"no matching function for call to [...]"
- 模板元程序查找相似的连续类型名称
- 如何在C++20中创建模板别名的推导指南
- 没有名称的C++模板参数
- 具有重复类型的C++可变模板
- 如何将enable-if与模板参数和参数包一起使用
- 没有用于初始化C++中的变量模板的匹配构造函数