C++模板化类的类型定义
C++ typedef for templated class
在
C++中为模板化类创建别名的最佳方法是什么?
template<typename T>
class Dummy1
{
public:
Dummy1(T var) : myVar1(var) {
}
~Dummy1() {
}
private:
T myVar1;
};
C 样式为:
typedef Dummy1<int> DummyInt;
据我所知,我会在C++中写道:
class DummyInt : public Dummy1<int>
{
DummyInt(int a) : Dummy1<int>(a) { }
~DummyInt() { }
}
有没有更好/更短的方法?因为当我从基继承时,我每次都必须声明构造函数。
我需要Dummy1<int>
的别名,否则我需要在整个代码(如指针和引用(中使用模板选项。但我不想这样做。
如果您只需要使用继承,那么您可以通过继承它们来避免在 c++11 及更高版本中重复构造函数:
struct DummyInt : Dummy1<int> {
using Dummy1::Dummy1;
};
否则,只需像您一样使用别名即可。如果你希望它不是"C方式",你可以采用现代C++风格:
using DummyInt = Dummy1<int>;
您也可以
使用 typedef 或 using in C++
typedef Dummy1<int> DummyInt;
using DummyInt = Dummy1<int>;
您在现代C++代码 IMO 中不再看到 typedef。
我更喜欢(C++11及之后(:
using DummyInt = Dummy1<int>;
在我看来,没有理由不在这里使用别名。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 列表参数的类型定义
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 关于 C++ 中的函数类型定义
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- 将使用/类型定义限制为类范围
- 模板类型定义?
- C++:模板类的类型定义
- 如何对命名空间限定类型进行类型定义?
- 此递归模板类型定义是否有效C++?
- 具有调整对齐方式的类型定义
- C++从抽象类型定义类成员
- 用于C++代码的 API 监视器类型定义 (XML)
- 如何将result_of与函数类型定义一起使用
- 在C++的适当类型定义位置
- 如何根据模板类型定义浮点常量?
- 如何为缺少预定义运算符而不扩展命名空间"std"的标准类型定义运算符>> (istream &, ...)?
- 参数化类的别名(或类型定义)内部类
- 如果我想从类型"T"定义元素的容器(来自 STL),那么"T"必须使用默认构造函数?