typedef 如何与模板一起使用?

How do typedefs work with templates?

我正在查看我的项目中的以下代码,但我似乎无法弄清楚数据是如何存储在下面的 typedef 中的。我是 C++ 的新手,所以对 typedef 和模板的了解有限。我搜索了对此类场景的良好描述,结果很少。

我的想法是,由 squareTemplate 生成的任何 typedef 都将具有 3 个值:面积、高度和宽度。但我不确定是什么 <bool, bool><std::vector<std ::pair<double, double>>,std::vector<std::pair<int, int>>> 做?是否所有 3 个 typedef 都包含面积、高度和宽度变量?请解释。

template <Class D, Class I>
struct squareTemplate
{
    I area;
    D height;
    D width;

   squareTemplate() :
    area(),
    height(),
    width()
    {
    }
};
typedef squareTemplate <std::vector<std ::pair<double, double>>, std::vector<std::pair<int, int>>> squareRange;

typedef squareTemplate <bool, bool> squareValid;

typedef squareTemplate<double, int> squareValue;

模板化的 class 是一种特殊的 class;它不是提供实现,而是基本上是编译器可以遵循的模式来创建 class 的版本(通常称为实例化 template)。我们以最后的 typedef (typedef squareTemplate<double, int> squareValue) 为例。你基本上得到了道德上等同于此的代码:

struct squareTemplate_double_int
{
    int area;
    double height;
    double width;

   squareTemplate() :
    area(),
    height(),
    width()
    {
    }
};

前两个 typedef 也会发生同样的事情:对于 template 类型的任何给定模式,您都会得到 squareTemplate 的唯一版本。

当你 typedef A B 你只是在说 B 是 A 的另一个名字。

Do all 3 typedefs contain area, height, and width variables?

是的。 squareTemplate 模板 class 被定义为具有 areaheightwidth,并且它的所有实例化都将具有这些成员。对于您的类型定义:

typedef squareTemplate <std::vector<std ::pair<double, double>>, std::vector<std::pair<int, int>>> squareRange;

area 具有第一个模板参数 D 假定的类型,因此 std::vector<std ::pair<double, double>>heightwidth 也是如此——它们具有第二个模板参数的类型,std::vector<std::pair<int, int>>

按照同样的推理,你得到:

typedef squareTemplate <bool, bool> squareValid;

都是bool

typedef squareTemplate<double, int> squareValue;

areaintheightwidthdouble

template <Class D, Class I>
struct squareTemplate
{
    I area;
    D height;
    D width;
    ...
}

首先:这不是"real"class。这是编译器可以用来生成 classes 的模板。给定模板参数 class Dclass I,编译器可以生成 "real" squareTemplate class.

typedef squareTemplate <double, int> squareValid;

这告诉编译器“使用带有模板参数 D=doubleI=intsquareTemplate 模板来生成 "real" 类型,我们将把它定义为squareValid 所以我们有一个合理的名称给这个类型。编译器填写 class 就像这样:

struct squareTemplate_double_int
{
    int area;
    double height;
    double width;
    ...
}
typedef squareTemplate_double_int squareValid;

不需要 typedef,如果需要,您可以直接使用它们:

void func() { 方形模板对象; }

但是当模板参数很长时,typedef 可以使事情变得简单:

typedef squareTemplate <std::vector<std ::pair<double, double>>, std::vector<std::pair<int, int>>> squareRange;
squareRange object;