C++模板概观
模板是C++的一种特性,允许函数或类通过泛型的形式表现或运行
函数模板可以似的函数或类在对应不同的型别的时候正常工作,而无需为每一个 为每一个型别都写一份代码
C++主要有两种类型的模板: 类模板和函数模板
模板实例化
实例化有两种类型
C++函数模板
template <class type>
ret-type func-name(parameter list)
{
// 函数的主体
}
常规模板,具体化模板,非模板函数的优先调用顺序。
非模板函数(普通函数)> 具体化模板函数 > 常规模板
总结
C++类模板
声明类模板的语法为
template<typename 类型参数1 , typename 类型参数2 , …>
class 类名{
//TODO:
};
一但声明了类模板,就可以将类型参数用于类的成员函数和成员变量了。
类模板的特化
//1. 标准模板类。
template<typename T1, typename T2> //MyClass<int,float> c1;
class MyClass {
public:
MyClass(){
std::cout<<" type 1. \n";
}
};
//2. 两个模板参数具有相同类型的部分特化类。
template<typename T> //MyClass<float,float> c2;
class MyClass<T,T> {
public:
MyClass(){
std::cout<<" type 2. \n";
}
};
//3. 第二个类型参数是int
template<typename T> //MyClass<float,int> c3;
class MyClass<T,int> {
public:
MyClass(){
std::cout<<" type 3. \n";
}
};
//4. 两个模板参数都是指针。
template<typename T1,typename T2> //MyClass<int*,float*> c4;
class MyClass<T1*,T2*> {
public:
MyClass(){
std::cout<<" type 4. \n";
}
};
//5. 两个模板参数都是相同类型的指针。
template<typename T> //MyClass<int*,int*> c5;
class MyClass<T*,T*> {
public:
MyClass(){
std::cout<<" type 5. \n";
}
};
//6. 调用示例代码。
int main() {
MyClass<int,float> c1; //调用MyClass<T1,T2>
MyClass<float,float> c2; //调用MyClass<T,T>
MyClass<float,int> c3; //调用MyClass<T,int>
MyClass<int*,float*> c4; //调用MyClass<T1*,T2*>
MyClass<int*,int*> c5; //调用MyClass<T*,T*>
MyClass<int,int> c6; // 调用MyClass<T,T> or 调用MyClass<T,int> , 报错:[Error] ambiguous class template instantiation for 'class MyClass<int, int>'
return 0;
}
默认模板实参
总结
C++操作符重载
具体规则
运算符 | 建议使用 |
所有一元运算符 | 成员函数 |
= ( ) [ ] -> | 必须是成员函数 |
+= -= /= *= ^= &= != %= >>= <<= , 似乎带等号的都在这里了 | 成员函数 |
所有其它二元运算符, 例如: –,+,*,/ | 友元函数 |
<< >> | 必须是友元函数 |
参数和返回值
当参数不会被改变,一般按const引用来传递(若是使用成员函数重载,函数也为const).
对于返回数值的决定:
1) 如果返回值可能出现在=号左边, 则只能作为左值, 返回非const引用。
2) 如果返回值只能出现在=号右边, 则只需作为右值, 返回const型引用或者const型值。
3) 如果返回值既可能出现在=号左边或者右边, 则其返回值须作为左值, 返回非const引用。
class Point
{
private:
int x;
public:
Point(int x1)
{ x=x1;}
Point(Point& p)
{ x=p.x;}
const Point operator+(const Point& p);//使用成员函数重载加号运算符
friend const Point operator-(const Point& p1,const Point& p2);//使用友元函数重载减号运算符
};
const Point Point::operator+(const Point& p)
{
return Point(x+p.x);
}
Point const operator-(const Point& p1,const Point& p2)
{
return Point(p1.x-p2.x);
}