模板总结

1、普通函数和函数模板区别

普通函数传入的形参类型是固定的,模板是任意类型

2、普通函数和函数模板调用规则

普通函数和函数模板都可以调用时,优先调用普通函数

空模板参数列表可以强制调用函数模板myprint<>(a, b);

函数模板也可以发生函数重载

如果函数模板可以产生更好的匹配,优先调用函数模板

3、函数模板并不是万能的

有些特定的数据结构需要具体的实现

比如:

 1 class person
 2 {
 3 public:
 4     person(string name, int age)
 5     {
 6         this->age = age;
 7         this->name = name;
 8     }
 9     string name;
10     int age;
11 };
12 //具体化的person实现比较
13 template<> bool mycompare(person &a, person &b)
14 {
15     if (a.age == b.age && a.name == b.name)
16         return true;
17     else
18         return false;
19 }
20 void test02()
21 {
22     person p1("tom", 10);
23     person p2("pel", 20);
24     bool ret = mycompare(p1, p2);
25     if (ret)
26         cout << "p1=p2" << endl;
27     else
28         cout << "p1!=p2" << endl;
29 }

4、函数模板和类模板区别

类模板:在类的前边加上 templete <class t>

类模板没有自动类型推导,person<string> p1(“zhang”, 18);  //必须指定类型

类模板在模板参数列表template <class NameType, class AgeType=int>,可以指定数据类型

5、类模板对象做函数参数

指定参数类型:void print1(person<string, int>&p)

参数模板化:

template <class t1, class t2>
void print2(person<t1, t2>&p)

整个类模板化:

template <class t1>
void print3(t1&p)

6、子类继承父类

class son :public base<int>  //必须知道父类类型

或者(子类模板):

template <class t1,class t2>
class son2 :public base<t2>

7、类模板成员函数类外实现

 1 template <class t1, class t2>
 2 class person
 3 {
 4 public:
 5     person(t1 name, t2 age);
 6     void show();
 7 
 8     t1 name;
 9     t2 age;
10 
11 };
12 
13 template <class t1, class t2>
14 person<t1,t2>::person(t1 name, t2 age)
15 {
16     this->age = age;
17     this->name = name;
18 }

 

Tags: