用汇编的眼光看C++(之模板类) (一)

2014-11-24 12:43:50 · 作者: · 浏览: 2

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

如果类是一种确定的数据类型,那么模板就是一种对类的抽象。假设有这么一种类,它需要进行数据的计算,而且类型还很多,那么我们可能就要针对不同类型的数据定义不同的类。我们可以用下面一段代码说明问题:

class int_process

{

int a;

int b;

public:

int_process(int m, int n):a(m), b(n) {}

~int_process() {}

int add() {return a + b;}

int sub() {return a - b;}

int mul() {return a * b;}

int div() {return a / b;}

};

class short_process

{

short a;

short b;

public:

short_process(short m, short n):a(m), b(n) {}

~short_process() {}

short add() {return a + b;}

short sub() {return a - b;}

short mul() {return a * b;}

short div() {return a / b;}

};

class int_process

{

int a;

int b;

public:

int_process(int m, int n):a(m), b(n) {}

~int_process() {}

int add() {return a + b;}

int sub() {return a - b;}

int mul() {return a * b;}

int div() {return a / b;}

};

class short_process

{

short a;

short b;

public:

short_process(short m, short n):a(m), b(n) {}

~short_process() {}

short add() {return a + b;}

short sub() {return a - b;}

short mul() {return a * b;}

short div() {return a / b;}

};

上面的代码内容其实比较简单,大家可以看明白。第一个类是int_process,主要是整数的加、减、乘、除的计算。第二类是short_process,主要处理的短整数的加、减、乘、除计算。两个类处理的内容其实非常相似。那么有没有一种简单的办法可以同时处理这两个类?有!这就是模板。我们可以把具体的数据类型抽象出来,形成一种新的类模式。这就是模板类。下面的代码就是模板类:

template

class data_process

{

type a;

type b;

public:

data_process(type m, type n):a(m), b(n) {}

~data_process() {}

type add() {return a + b;}

type sub() {return a - b;}

type mul() {return a * b;}

type div() {return a / b;}

};

template

class data_process

{

type a;

type b;

public:

data_process(type m, type n):a(m), b(n) {}

~data_process() {}

type add() {return a + b;}

type sub() {return a - b;}

type mul() {return a * b;}

type div() {return a / b;}

};

我们看到类把具体的数据类型都抽象成了type。至此,不管是输入值、输出数值,我们都换成了type。至于类的名称,我们也从原来特定的数据类型计算,转变成了通用的data_process,当然这种名称的定义不是太重要的。那么模板类定义之后,我们应该怎么应用呢?大家继续看代码:

void process()

{

data_process d(1,2);

data_process m('1', '2');

data_process p(1.2, 2.3);

}

void process()

{

data_process d(1,2);

data_process m('1', '2');

data_process p(1.2, 2.3);

} 大家从上面的代码也看的出,模板类的定义并不复杂,只是在模板类的名称之后添加一下具体的数据类型就可以了。如果是int类型的,那么处理int的数据;同理,如果处理的是char或者是double类型数据,我们就可以按照char或者是double类型的数据进行计算,十分方便。当谈,处理的数据远远不止C++语言本身定义的char、double、float、int、short、long这几种数据类型,如果type本身就是一种class类型,同时这样class类型也支持+、-、*、/运算,那么本身也是可以用作模板的。我们这里介绍int、char、double只是为了简单地说明问题。看到类的声明后,我们不禁有一个疑问,既然模板类只有一个,那么这些模板类的构造函数、析构函数、成员函数的处理都相同吗?我们不妨看看看一看他们的汇编代码:

60: data_process d(1,2);

0040126D push 2

0040126F push 1

00401271 lea ecx,[ebp-14h]

00401274 call @ILT+45(data_process::data_process) (00401032)

00401279 mov dword ptr [ebp-4],0

61: data_process m('1', '2');

00401280 push 32h

00401282 push 31h

00401284 lea ecx,[ebp-18h]

00401287 call @ILT+55(data_process::data_process) (0040103c)

0040128C mov byte ptr [ebp-4],1

62: data_process p(1.2, 2.3);

00401290 push 40026666h

00401295 push