第十天2017/04/21(2、泛型编程:模板 / 全特化、偏特化)

来源:互联网 发布:工科博士毕业年薪 知乎 编辑:程序博客网 时间:2024/06/16 21:49
1、什么是模板?  template<class T1,class T2,.....>类属————类型参数化,又称参数模板    使得程序可以从逻辑功能上抽象,把被处理的对象(数据)的类型作为参数传递。【1】函数模板#include <iostream>using namespace std;//函数模板template <class T1,class T2>void show(T1 a,T2 b){    cout<<a<<"+"<<b<<endl;}int main(){//自动类型推导    show(111,2.222);//具体类型调用    show<int,float>(111,2.222); //类型参数化}【注意】    函数模板可以像普通函数一样被重载    函数模板不允许自动类型的转换,普通函数可以进行自动类型转换【C++编译器怎么实现函数模板的?】函数模板实现本质探究!    ——编译器并不是把函数模板处理成能够处理任意类型的函数    --编译器从函数模板通过具体类型产生不同的函数    --编译器会对函数模板进行两次编译    --在调用的地方对参数替换后的代码进行编译换句话说:只不过是C++编译器帮我们写出了自己想要的函数而已!【2】类模板知识1.类模板遇上继承#include <iostream>using namespace std;//类模板template <class T1,class T2>class A{public:    void show(T1 a,T2 b);};template <class T1,class T2>void A<T1,T2>::show(T1 a,T2 b){    cout<<a<<"+"<<b<<endl;}//继承类模板的语法:类A必须类型具体化为A<int,int>class B:public A<int,int> {public:    void show_B(int a,int b);};template <class T1,class T2>void B::show_B(int a,int b){    cout<<a<<"+"<<b<<endl;}int main(){    A<int,char> a; //必须把类模板具体化类型后,才能实例化    a.show(1,'A');    //继承类模板    B b;    b.show_B(100,200);}
知识2:类模板遇上友元函数    在类模板中,如果有友元函数,那么该友元函数的实现必须在类中进行(如果在类外实现不管用何种方式,都会编译错误)。#include <iostream>using namespace std;template <class T>class Complex{public://类的成员函数    Complex(T r=0, T i=0);    void print();//类的友元函数    friend Complex operator+(const Complex<T> &c1,const Complex<T> &c2)    {        return Complex<T>(c1.real+c2.real,c1.imag+c2.imag);    }    friend ostream& operator<<(ostream& out,const Complex& c)    {        out<<c.real<<"+"<<c.imag;        return out;    }private:    T real;    T imag;};//成员函数template<class T> Complex<T>::Complex(T r=0,T i=0)  {    real = r;    imag =i;}//成员函数template<class T>void Complex<T>::print(){    cout<<real<<"+"<<imag<<endl;}int  main(){    Complex<int> c1(1,1);    Complex<int> c2(2,2);    Complex<int> c3;    c3 = c1+c2;    c3.print();    cout<<c3<<endl;    return 0;}
知识3:类模板遇上static静态成员//每一种类型A<int>、A<char>、A<float>对应自己各自的静态成员#include <iostream>using namespace std;template<class T>class A{public:    A();    static int get_count();    ~A();private:    static int count;};//下面是成员属性的初始化、成员函数的实现template<class T>int A<T>::count = 0;template<class T>A<T>::A(){    count++;}template<class T>int A<T>::get_count(){    return count;}template<class T>A<T>::~A(){    count--;}int main(){    A<int> a1;    A<int> a2;    A<int> a3;    cout<<A<int>::get_count()<<endl;  //3个A<int>类型的对象---------------------------------------------------------------    A<char> aa1;    A<char> aa2;    cout<<A<char>::get_count()<<endl; //2个A<char>类型的对象}

(函数/类模板)的(偏特化/全特化)
详解见C++中的博客

1 0