操作符重载and模板(泛化, 全特化, 偏特化)

模板

Header(头文件)中的防卫式声明、布局

// complex.h

// guard 防卫式声明
#ifndef __COMPLEX__
#define __COMPLEX__

// 0、forward declarations (前置声明)
#include <cmath>

class ostream;
class complex;

complex&
    __doapl (complex* ths, const complex& r);

// 1、class declarations (类-声明)
class complex
{
    ...
};

// 2、class definition (类-定义)
complex::function ...

#endif
// complex-test.cpp

#include <iostream>
#incldue "complex.h" // *****HERE*****
using namespace std;

int main() {
    ...
}

class - 声明

class complex // class head
{ // class body
public:
    complex (double r = 0, double i = 0) 
        : re (r), im (i) 
    {  }
    // 有些函数在此直接定义,另一些在body之外定义
    complex& operator += (const complex&) ;
    double real () const { return re; }
    double imag () const { return im; }
private:
    double re, im;

    friend complex& __doapl (complex*, const complex&);

};

// .cpp
{
    complex c1(2,1);
    complex c2;
}

类模板

template<typename T>
class complex // class head
{ // class body
public:
    complex (T r = 0, Ti = 0) 
        : re (r), im (i) 
    {  }
    // 有些函数在此直接定义,另一些在body之外定义
    complex& operator += (const complex&) ;
    T real () const { return re; }
    T imag () const { return im; }
private:
    T re, im;

    friend complex& __doapl (complex*, const complex&);

};
// .cpp
{
    complex<double> c1(2.5,1.5);
    complex<int> c2(2,6);
}

函数模板

stone r1(2, 3), r2(3, 3), r3;
r3 = min(r1, r2);
template <class T>
inline
const T& min(const T& a, const T& b)
{
	return b < a ? b : a;
}
class stone
{
public:
	stone(int w, int h, int we)
	  : _w(w), _h(h), _weight(we)
	    {	}
	bool operator<const stone& rhs) const
		{return _weight < rhs. _weight;}
private:
	int _w, _h, _weight;
}

操作符重载

头文件

#ifndef __COMPLEX__ // 1.防卫式声明
#define __COMPLEX__	

#include <iostream>
using std::ostream;

// 2.class head
class complex 
{ // class body
public:
	// 3.构造函数 inline
	complex (double r = 0, double i = 0) // pass by 什么都可以,因为double是4个字节
		: re(r), im(i) // 设初值
	{  }
	// 有些函数在此直接定义,另一些在body之外定义
	complex& operator += (const complex&); // 5.重载+=,设计为成员函数
	// 4.取得实部和虚部,不会改data,所以函数是const;inline
	double real() const { return re; } 
	double imag() const { return im; }
private:
	double re, im;
	// 6.do assignment-plus 函数中想直接取得re和im,所以声明成友元函数
	friend complex& __doapl(complex*, const complex&);
};

#endif // __COMPLEX__

cpp文件

#include "complex.h"


// 重载+=
// 想法类似下面
inline complex&
__doapl(complex* ths, const complex& r) {
	ths->re += r.re;
	ths->im += r.im;
	return *ths;
}

// +=左边是默认的this指针;
// 右边最好引用&,不改变右边,所以const;
// 返回值不是局部变量,可以传引用&;
// 希望成为inline函数
inline complex&
complex::operator += (const complex& r) {
	return __doapl(this, r);
}

// 重载 +,非成员函数:因为不一定就是复数加复数,可以实数加复数
// 因为不能加到x和y上,所以会加到一个新的局部变量上,所以return by value
inline complex
operator + (const complex& x, const complex& y) {
	return complex(x.real() + y.real(), x.imag() + y.imag());
}

inline complex
operator + (double x, const complex& y) {
	return complex(x + y.real(), y.imag());
}

inline complex
operator + (const complex& x, double y) {
	return complex(x.real() + y, x.imag());
}

// 重载 <<
// 因为不可以写成 c1 << cout,所以要写成非成员函数
// os传进来以后,每次输出一点东西,就会改变,所以是&
// 返回ostream 是为了可以连续输出;ostream 不是局部变量,可以返回引用
// 为了使用ostream,要 #include <iostream>
inline ostream& 
operator << (ostream& os, const complex& x) {
	return os << "(" << x.real() << "," << x.imag() << ")";
}


模板特化

概述

模板特化(template specialization)不同于模板的实例化,模板参数在某种特定类型下的具体实现称为模板特化。模板特化有时也称之为模板的具体化,分别有函数模板特化和类模板特化。

函数模板特化

函数模板特化指函数模板在模板参数为特定类型下的特定实现。查看以下示例:

#include <iostream>
using namespace std;

template<typename T> T Max(T t1,T t2) {
	return (t1>t2)?t1:t2;
}

typedef const char* CCP;
template<> CCP Max<CCP>(CCP s1,CCP s2) {
	return (strcmp(s1,s2)>0)?s1:s2;
}

int main() {
	// 隐式调用实例:int Max<int>(int,int)
	int i=Max(10,5);
	

	// 显式调用特化版本:const char* Max<const char*>(const char*,const char*)
	const char* p=Max<const char*>("very","good");
	cout<<"i:"<<i<<endl;
	cout<<"p:"<<p<<endl;

}

程序正常编译运行结果:

i:10
p:very

在函数模板显示特化定义(Explicit Specialization Definition)中,显示关键字 template 和一对尖括号 <>,然后是函数模板特化的定义。该定义指出了模板名、被用来特化模板的模板实参,以及函数参数表和函数体。在上面的程序中,如果不给出函数模板Max< T>在T为const char*时的特化版本,那么在比较两个字符串的大小时,比较的是字符串的起始地址的大小,而不是字符串的内容在字典序中的先后次序。

除了定义函数模板特化版本外,还可以直接给出模板函数在特定类型下的重载形式(普通函数)。使用函数重载可以实现函数模板特化的功能,也可以避免函数模板的特定实例的失效。例如,把上面的模板特化可以改成如下重载函数。

typedef const char* CCP;
CCP Max(CCP s1,CCP s2) {
	return (strcmp(s1,s2)>0)?s1:s2;
}

程序运行结果和使用函数模板特化相同。但是,使用普通函数重载和使用模板特化还是有不同之处,主要表现在如下两个方面:

(1)如果使用普通重载函数,那么不管是否发生实际的函数调用,都会在目标文件中生成该函数的二进制代码。而如果使用模板的特化版本,除非发生函数调用,否则不会在目标文件中包含特化模板函数的二进制代码。这符合函数模板的“惰性实例化”准则。

(2)如果使用普通重载函数,那么在分离编译模式下,需要在各个源文件中包含重载函数的申明,否则在某些源文件中就会使用模板函数,而不是重载函数。

类模板特化

类模板特化类似于函数模板的特化,即类模板参数在某种特定类型下的具体实现。考察如下代码:

#include <iostream>
using namespace std;

template<typename T>class A {
	T num;
public:
	A(){
		num=T(6.6);
	}
	void print(){
		cout<<"A'num:"<<num<<endl;
	}
};

template<> class A<char*> {
	char* str;
public:
	A() {
		str="A' special definition ";
	}
	void print() {
		cout<<str<<endl;
	}
};

int main() {
	A<int> a1;      //显示模板实参的隐式实例化
	a1.print();
	A<char*> a2;    //使用特化的类模板
	A2.print();
}

程序输出结果如下:

A'num:6
A' special definition

模板偏特化

概述

模板偏特化(Template Partitial Specialization)是模板特化的一种特殊情况,指显示指定部分模板参数而非全部模板参数,或者指定模板参数的部分特性分而非全部特性,也称为模板部分特化。与模板偏特化相对的是模板全特化,指对所有模板参数进行特化。模板全特化与模板偏特化共同组成模板特化。

模板偏特化主要分为两种,一种是指对部分模板参数进行全特化,另一种是对模板参数特性进行特化,包括将模板参数特化为指针、引用或是另外一个模板类。

函数模板偏特化

假如我们有一个 compare 函数模板,在比较数值大小时没有问题,如果传入的是数值的地址,我们需要比较两个数值的大小,而非比较传入的地址大小。此时我们需要对 compare 函数模板进行偏特化。考察如下代码:

#include <vector>
#include <iostream> 
using namespace std;

// 函数模板
template<typename T, class N> void compare(T num1, N num2) {
	cout << "standard function template" << endl;
	if(num1>num2) {
		cout << "num1:" << num1 << " > num2:" << num2 <<endl;
	} else {
		cout << "num1:" << num1 << " <= num2:" << num2 << endl;
	}
}

// 对部分模板参数进行特化
template<class N> void compare(int num1, N num2) {
	cout<< "partitial specialization" <<endl;
	if (num1>num2)
		cout << "num1:" << num1 << " > num2:" << num2 << endl;
	else
		cout << "num1:" << num1 << " <= num2:" << num2 << endl;
}

// 将模板参数特化为指针(模板参数的部分特性)
template<typename T, class N> void compare(T* num1, N* num2) {
	cout << "new partitial specialization" << endl;
	if (*num1>*num2)
		cout << "num1:" << *num1 << " > num2:" << *num2 << endl;
	else
		cout << "num1:" << *num1 << " <= num2:" << *num2 << endl;
}

// 将模板参数特化为另一个模板类
template<typename T, class N> void compare(std::vector<T>& vecLeft, std::vector<T>& vecRight) {
	cout << "to vector partitial specialization" << endl;
	if (vecLeft.size()>vecRight.size())
		cout << "vecLeft.size()" << vecLeft.size() << " > vecRight.size():" << vecRight.size() << endl;
	else
		cout << "vecLeft.size()" << vecLeft.size() << " <= vecRight.size():" << vecRight.size() << endl;
}

int main() {
	// 调用非特化版本 compare<int,int>(int num1, int num2)
	compare<int,int>(30,31);

	// 调用偏特化版本 compare<char>(int num1, char num2)
	compare(30,'1');
	
	int a = 30;
	char c = '1';
	// 调用偏特化版本 compare<int,char>(int* num1, char* num2)
	compare(&a, &c);
	
	vector<int> vecLeft{0};
	vector<int> vecRight{1,2,3};
	// 调用偏特化版本 compare<int,char>(int* num1, char* num2)
	compare<int,int>(vecLeft,vecRight);

}

程序输出结果如下:

standard function template
num1:30 <= num2:31
partitial specialization
num1:30 <= num2:1
new partitial specialization
num1:30 <= num2:1
to vector partitial specialization
vecLeft.size()1 <= vecRight.size():3

类模板偏特化

类模板的偏特化与函数模板的偏特化类似。考察如下代码:

#include <vector>
#include <iostream> 
using namespace std;

// 类模板
template<typename T, class N> class TestClass {
public:
	static bool comp(T num1, N num2) {
		cout <<"standard class template"<< endl;
		return (num1<num2) ? true : false;
	}
};

// 对部分模板参数进行特化
template<class N> class TestClass<int, N> {
public:
	static bool comp(int num1, N num2) {
		cout << "partitial specialization" << endl;
		return (num1<num2) ? true : false;
	}
};

// 将模板参数特化为指针
template<typename T, class N> class TestClass<T*, N*> {
public:
	static bool comp(T* num1, N* num2) {
		cout << "new partitial specialization" << endl;
		return (*num1<*num2) ? true : false;
	}
};

// 将模板参数特化为另一个模板类
template<typename T, class N> class TestClass<vector<T>,vector<N>> {
public:
	static bool comp(const vector<T>& vecLeft, const vector<N>& vecRight) {
		cout << "to vector partitial specialization" << endl;
		return (vecLeft.size()<vecRight.size()) ? true : false;
	}
};

int main() {
	// 调用非特化版本
	cout << TestClass<char, char>::comp('0', '1') << endl;	
	

	// 调用部分模板参数特化版本
	cout << TestClass<int,char>::comp(30, '1') << endl;		
	
	// 调用模板参数特化为指针版本
	int a = 30;
	char c = '1';
	cout << TestClass<int*, char*>::comp(&a, &c) << endl;		
	
	// 调用模板参数特化为另一个模板类版本
	vector<int> vecLeft{0};
	vector<int> vecRight{1,2,3};
	cout << TestClass<vector<int>, vector<int>>::comp(vecLeft,vecRight) << endl;	

}

程序输出结果:

standard class template
1
partitial specialization
1
new partitial specialization
1
to vector partitial specialization
1

参考
[1]侯捷c++
[2]C++ 模板特化与偏特化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值