现在的位置: 首页 > 综合 > 正文

简单指导C++ Templates

2013年07月01日 ⁄ 综合 ⁄ 共 2360字 ⁄ 字号 评论关闭

1. 模板的基本语法

模板通常是用一对尖括号给括起来。

如: < Content >

Content内容可以是:

a)       class T / typename T

b)        一种数据类型,关联T

其中T 就是代表了一种数据类型。

下面用一个几段代码来演示一下

void PrintTwice(int data)
{
    cout << "Twice is: " << data * 2 << endl;         
}

 通过 传递一个int 类型的参数调用

PrintTwice(120); // 240

 

那么当你想计算double类型的时候你就要重新写一个新函数

 

void PrintTwice(double data)
{
    cout << "Twice is: " << data * 2 << endl;         
}

在这里比较幸运的的是 ostream,基本类型都支持。

完整代码如下

// test_template.cpp : 定义控制台应用程序的入口点。
// by wallwind on sunrise 2011/10/22

#include "stdafx.h"
#include <iostream>
using namespace std;

void PrintTwice(int data)
{
	cout << "Twice is: " << data * 2 << endl;         
}

void PrintTwice(double data)
{
	cout << "Twice is: " << data * 2 << endl;         
}

int _tmain(int argc, _TCHAR* argv[])
{
	PrintTwice(2);
	PrintTwice(2.2);
	return 0;
}

 

看上去,函数的重载是非常好的。但是由于只有一处改动,造成了代码的冗余。因此,我们提出了模板。

模板分为:

  • 函数模板
  • 类模板

有了模板我们可以通过使用我们想要的类型进行调用。而不是通过复制函数来完成我们的任务

下面讲解一下函数模板,首先把等同于上一个效果的实例代码给出

// test_template.cpp : 定义控制台应用程序的入口点。
// by wallwind on sunrise 2011/10/22

#include "stdafx.h"
#include <iostream>
template<typename TYPE>
TYPE Twice(TYPE data)
{
   return data * 2;
}

using namespace std;template<class type>void PrintTwice(type data){cout<<"Twice: " << data * 2 << endl;}int _tmain(int argc, _TCHAR* argv[]){PrintTwice(2);PrintTwice(2.2);return 0;}


结果是一样的,这里使用的代码就非常的简洁了。

template<class TYPE>  这行代码通知编译器这是一个函数模板。符号TYPE 将会通过编译器推断出传值过来的数据类型。TYPE 被称为template type parameter.

因此当我调用

PrintTwice(2);

的时候,TYPE将会被替换成 int数据类型,编译器将会把模板函数写成

void PrintTwice(int data)
{
    cout<<"Twice: " << data * 2 << endl;
}

同理当我们调用

PrintTwice(2.2);

的时候就会使用

 

以上两个函数都是通过数据类型推导出来的,也就是重载了函数。它们都是通过编译器来完成的。而不是通过你手工的复制并修改代码。

 

下面再来看看另一个函数:

template<typename TYPE>
TYPE Twice(TYPE data)
{
   return data * 2;
}

 

我们注意到我用typename 替换了class。但是这不是因为我们有了返回类型。其实这两个类型是很相似的。几乎无差别。

我们可以如下调用:

cout << Twice(10);
cout << Twice(3.14);
cout << Twice( Twice(55) );

编译器会自动给我生成如下:

int     Twice(int data) {..}
double  Twice(double data) {..}

注意两点

•In third line of code snipped above, Twice is called twice - the return value/type of first call would be the argument/type of second call. Hence, both calls are of int type.
•If a template function is instantiated for a particular data-type, compiler would re-use the same function' instance, if the function is invoked again for same data-type. It means, irrespective of where in your code you invoke the function template with same
type - in same function, in different function, or anywhere in another source file (of same project/build).

 

在上边的第三行代码中,Twice函数调用了两次。第一次调用返回值将作为其参数的类型。

如果模板函数被实例化特殊的数据类型,编译器将会重复使用同样的函数实例。

Let's write up a function template that would return the addition of two numbers:

template<class T>
T Add(T n1, T n2)
{
    return n1 + n2;
}

今天翻译到此,明天继续。

更多请访问:http://blog.csdn.net/wallwind

抱歉!评论已关闭.