typedef如何使用模板?

时间:2018-03-07 01:46:26

标签: c++ templates struct typedef

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

我的想法是使用squareTemplate制作的任何typedef都有3个值:area,height和width。但我不确定是什么 <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;

3 个答案:

答案 0 :(得分:4)

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

  

所有3个typedef都包含面积,高度和宽度变量吗?

是。 squareTemplate模板类定义为areaheightwidth,其所有实例都将包含这些成员。对于你的typedef:

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;

areaint; heightwidthdouble

答案 1 :(得分:1)

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

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

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

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

答案 2 :(得分:0)

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

首先:这不是一个“真正的”类。这是编译器可用于创建类的模板。给定模板参数class Dclass I,编译器可以生成“真正的”squareTemplate类。

typedef squareTemplate <double, int> squareValid;

这告诉编译器“使用squareTemplate模板和模板参数D=doubleI=int来生成”真实“类型,我们将其键入到{{1}所以我们对这个类型有一个合理的名称。编译器将类填充为类似:

squareValid

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

void func(){        squareTemplate对象;    }

但是当模板参数很难输入时,typedef可以保持简单:

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