当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++ 模板常见特性(函数模板、类模板)

C++ 模板常见特性(函数模板、类模板)

2020年01月09日  | 移动技术网IT编程  | 我要评论

乳交之霸,嗜血妖王的宠妃,曾海潮 李悦

背景

c++ 是很强大,有各种特性来提高代码的可重用性,有助于减少开发的代码量和工作量。

c++ 提高代码的可重用性主要有两方面:

  • 继承
  • 模板

继承的特性我已在前面篇章写过了,本篇主要是说明「模板」的特性。

使用「模板」的特性设计,实际上也就是「泛型」程序设计。

函数模板

01 变量交换函数模板

假设我们设计一个交换两个整型变量的值的函数,代码如下:

// 交换两个整型变量的值的swap函数:
void swap(int & x,int & y)
{
    int tmp = x;
    x = y;
    y = tmp;
}

如果是浮点类型的变量的值交换,则替换 int 类型为 double 即可,代码如下:

// 交换两个double型变量的值的swap函数:
void swap(double & x,double & y)
{
    double tmp = x;
    x = y;
    y = tmp;
}

那如果是其他变量类型的值交换,那不是每次都要重新写一次 swap 函数?是不是很繁琐?且代码后面会越来越冗余。

能否只写一个 swap 函数,就能交换各种类型的变量?

答案是肯定有的,就是用「函数模板」来解决,「函数模板」的形式:

template <class 类型参数1,class 类型参数2,...>
返回值类型 模板名 (形参表)
{
    函数体
};

具体 swap 「函数模板」代码如下:

template 就是模板定义的关键词,t 代表的是任意变量的类型。

template <class t>
void swap(t & x,t & y)
{
    t tmp = x;
    x = y;
    y = tmp;
}

那么定义好「函数模板」后,在编译的时候,编译器会根据传入 swap 函数的参数变量类型,自动生成对应参数变量类型的 swap 函数:

int main()
{
    int n = 1,m = 2;
    swap(n,m); //编译器自动生成 void swap(int & ,int & )函数
    
    double f = 1.2,g = 2.3;
    swap(f,g); //编译器自动生成 void swap(double & ,double & )函数
    
    return 0;
}

上面的实例化函数模板的例子,是让编译器自己来判断传入的变量类型,那么我们也可以自己指定函数模板的变量类型,具体代码如下:

int main()
{
    int n = 1,m = 2;
    swap<int>(n,m);     // 指定模板函数的变量类型为int
    
    double f = 1.2,g = 2.3;
    swap<double>(f,g); // 指定模板函数的变量类型为double
    
    return 0;
}

02 查询数组最大值函数模板

在举一个例子,下面的 maxelement 函数定义成了函数模板,这样不管是 int、double、char 等类型的数组,都可以使用该函数来查数组最大的值,代码如下:

// 求数组最大元素的maxelement函数模板
template <class t>
t maxelement(t a[], int size) // size是数组元素个数
{
    t tmpmax = a[0];
    for(int i = 1;i < size;++i)
    {
        if(tmpmax < a[i])
        {
            tmpmax = a[i];
        }
    }
    return tmpmax;
}

03 多个类型参数模板函数

函数模板中,可以不止一个类型的参数:

template <class t1, class t2>
t2 myfun(t1 arg1, t2 arg2)
{
    cout<< arg1 << " "<< arg2<<endl;
    return arg2;
}

t1 是传入的第一种任意变量类型,t2 是传入的第二种任意变量类型。


04 函数模板的重载

函数模板可以重载,只要它们的形参表或类型参数表不同即可。

// 模板函数 1
template<class t1, class t2>
void print(t1 arg1, t2 arg2) 
{
    cout<< arg1 << " "<< arg2<<endl;
}

// 模板函数 2
template<class t>
void print(t arg1, t arg2) 
{
    cout<< arg1 << " "<< arg2<<endl;
}

// 模板函数 3
template<class t,class t2>
void print(t arg1, t arg2) 
{
    cout<< arg1 << " "<< arg2<<endl;
}

上面都是 print(参数1, 参数2) 模板函数的重载,因为「形参表」或「类型参数表」名字不同。

05 函数模板和函数的次序

在有多个函数和函数模板名字相同的情况下,编译器如下规则处理一条函数调用语句:

  1. 先找参数完全匹配的普通函数(非由模板实例化而得的函数);
  2. 再找参数完全匹配的模板函数;
  3. 再找实参数经过自动类型转换后能够匹配的普通函数;
  4. 上面的都找不到,则报错。

代码例子如下:

// 模板函数 - 1个参数类型
template <class t>
t max(t a, t b) 
{
    cout << "templatemax" <<endl; return 0;
}

// 模板函数 - 2个参数类型
template <class t, class t2>
t max(t a, t2 b) 
{
    cout << "templatemax2" <<endl; return 0;
}

// 普通函数
double max(double a, double b)
{
    cout << "mymax" << endl;
    return 0;
}

int main() 
{
    int i=4, j=5;
    
    // 输出mymax - 匹配普通函数
    max( 1.2, 3.4 ); 
    
    //输出templatemax - 匹配参数一样的模板函
    max( i, j );
    
    //输出templatemax2 - 匹配参数类型不同的模板函数
    max( 1.2, 3 );   
    
    return 0;
}

匹配模板函数时,当模板函数只有一个参数类型时,传入了不同的参数类型,是不进行类型自动转换,具体例子如下:

// 模板函数 - 1个参数类型
template<class t>
t myfunction( t arg1, t arg2)
{ 
    cout<<arg1<<" "<<arg2<<"\n"; 
    return arg1;
}

...

// ok :替换 t 为 int 类型
myfunction( 5, 7); 

// ok :替换 t 为 double 类型  
myfunction(5.8, 8.4);

// error :没有匹配到myfunction(int, double)函数
myfunction(5, 8.4); 

类模板

01 类模板的定义

为了多快好省地定义出一批相似的类,可以定义「类模板」,然后由类模板生成不同的类

类模板的定义形式如下:

template <class 类型参数1,class 类型参数2,...> //类型参数表
class 类模板名
{
   成员函数和成员变量
};

用类模板定义对象的写法:

类模板名<真实类型参数表> 对象名(构造函数实参表);

02 pair类模板例子

接下来,用 pair 类用类模板的方式的实现,pair 是一对的意思,也就是实现一个键值对(key-value)的关系的类。

// 类模板
template <class t1, class t2>
class pair
{
public:
    pair(t1 k, t2 v):m_key(k),m_value(v) {};
    bool operator < (const pair<t1,t2> & p) const;
private:
    t1 m_key;
    t2 m_value;
};

// 类模板里成员函数的写法
template <class t1, class t2>
bool pair<t1,t2>::operator < (const pair<t1,t2> &p) const
{
    return m_value < p.m_value;
}

int main()
{
    pair<string,int> astudent("jay",20); 
    pair<string,int> bstudent("tom",21);
    
    cout << (astudent < bstudent) << endl;
    
    return 0;
}

输出结果:

1

需要注意的是,同一个类模板的两个模板类是不兼容的:

pair<string,int> *p;
pair<string,double> a;
p = & a; //错误!!

03 函数模板作为类模板成员

当函数模板作为类模板的成员函数时,是可以单独写成函数模板的形式,成员函数模板在使用的时候,编译器才会把函数模板根据传入的函数参数进行实例化,例子如下:

// 类模板
template <class t>
class a
{
public:
    template<class t2>
    void func(t2 t) { cout << t; } // 成员函数模板
};

int main()
{
    a<int> a;
    a.func('k');     //成员函数模板 func被实例化
    a.func("hello"); //成员函数模板 func再次被实例化

    return 0;
} 

04 类模板与非类型参数

类模板的“<类型参数表>”中可以出现非类型参数:

template <class t, int size>
class carray
{
public:
    void print( )
    {
        for( int i = 0;i < size; ++i)
        cout << array[i] << endl;
    }
private:
    t array[size];
};

carray<double,40> a2;
carray<int,50> a3; //a2和a3属于不同的类

类模板与派生

01 类模板从类模板派生

上图的代码例子如下:

// 基类 - 类模板
template <class t1,class t2>
class a 
{
    t1 v1; t2 v2;
};

// 派生类 - 类模板
template <class t1,class t2>
class b:public a<t2,t1> 
{
    t1 v3; t2 v4;
};

// 派生类 - 类模板
template <class t>
class c:public b<t,t> 
{
    t v5;
};

int main() 
{
    b<int,double> obj1; 
    c<int> obj2;
    return 0;
}

02 类模板从模板类派生

上图的代码例子如下:

template <class t1,class t2>
class a 
{
    t1 v1; t2 v2;
};

template <class t>
class b:public a<int,double>  // a<int,double> 模板类
{
    t v;
};

int main() 
{
    //自动生成两个模板类 :a<int,double> 和 b<char>
    b<char> obj1;
    return 0;
}

03 类模板从普通类派生

上图的代码例子如下:

// 基类 - 普通类
class a 
{
    int v1;
};

// 派生类 - 类模板
template <class t>
class b:public a  // 所有从b实例化得到的类 ,都以a为基类
{ 
    t v;
};

int main() 
{
    b<char> obj1;
    return 0;
}

04 普通类从模板类派生

上图的代码例子如下:

template <class t>
class a 
{
    t v1;
};

class b:public a<int> 
{
    double v;
};

int main() 
{
    b obj1;
    return 0;
}

类模板与友元

01 函数、类、类的成员函数作为类模板的友元

代码例子如下:

// 普通函数
void func1() { } 

// 普通类
class a { }; 

// 普通类
class b 
{
    public:
    void func() { } // 成员函数
};

// 类模板
template <class t>
class tmp
{
    friend void func1();    // 友元函数
    friend class a;         // 友元类
    friend void b::func();  // 友元类的成员函数
}; // 任何从 tmp 实例化来的类 ,都有以上三个友元

02 函数模板作为类模板的友元

// 类模板
template <class t1,class t2>
class pair
{
private:
    t1 key;   //关键字
    t2 value; //值
public:
    pair(t1 k,t2 v):key(k),value(v) { };
    
    // 友元函数模板
    template <class t3,class t4>
    friend ostream & operator<< (ostream & o, const pair<t3,t4> & p);
};

// 函数模板
template <class t3,class t4>
ostream & operator<< (ostream & o, const pair<t3,t4> & p)
{
    o << "(" << p.key << "," << p.value << ")" ;
    return o;
}

int main()
{
    pair<string,int> student("tom",29);
    pair<int,double> obj(12,3.14);
    
    cout << student << " " << obj;
    return 0;
}

输出结果:

(tom,29) (12,3.14)

03 函数模板作为类的友元

// 普通类
class a
{
private:
    int v;
public:
    a(int n):v(n) { }
    
    template <class t>
    friend void print(const t & p); // 函数模板
};

// 函数模板
template <class t>
void print(const t & p)
{
    cout << p.v;
}

int main() 
{
    a a(4);
    print(a);
    return 0;
}

输出结果:

4

04 类模板作为类模板的友元

// 类模板
template <class t>
class b 
{
private:
    t v;
public:
    b(t n):v(n) { }
    
    template <class t2>
    friend class a; // 友元类模板
};

// 类模板
template <class t>
class a 
{
public:
    void func( )  
    {
        b<int> o(10); // 实例化b模板类
        cout << o.v << endl;
    }
};

int main()
{
    a<double> a;
    a.func ();
    return 0;
}

输出结果:

10

类模板与静态成员变量

类模板中可以定义静态成员,那么从该类模板实例化得到的所有类,都包含同样的静态成员。

template <class t>
class a
{
private:
    static int count; // 静态成员
public:
    a() { count ++; }
    ~a() { count -- ; };
    a( a & ) { count ++ ; }
    
    static void printcount() { cout << count << endl; } // 静态函数
};

template<> int a<int>::count = 0;    // 初始化
template<> int a<double>::count = 0; // 初始化

int main()
{
    a<int> ia;  
    a<double> da; // da和ia不是相同模板类
    ia.printcount();
    da.printcount();
    return 0;
}

输出:

1
1

上面的代码需要注意的点:

  • 类模板里的静态成员初始化的时候,最前面要加template<>
  • ia 和 da 对象是不同的模板类,因为类型参数是不一致,所以也就是不同的模板类。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网