C++模板化类的类型定义

C++ typedef for templated class

本文关键字:类型 定义 C++      更新时间:2023-10-16

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

在我看来,没有理由不在这里使用别名。