template<class T,class U> //泛化版本 =>参数只要是类型就可以 但是不能是模板类型
class Test
{
public:
Test() {cout<<"T U"<<endl;}
};
template<class T,class U>
class Test<T*,U*> //比上面的调用范围小 部分特化 运行全部为指针
{
public:
Test(){cout<<"T * U *"<<endl;}
};
template<>
class Test<char *,char*> //完全特化
{
public:
Test(){cout<<"char* char* "<<endl;}
};
int main()
{
Test<int,int> c1;
Test<int*,int *> c2;
Test<int,char> c3;
Test<int*,char*> pic; //只能调动<*,*>
Test<char*,char*> cpp; //完全特化
}
template<class _Ty>
struct my_remove_reference
{
my_refemove_reference()
{
int x=10;
_Ty y=x; //_Ty
}
};
template<class _Ty>
struct my_remove_reference<_Ty&> //将引用特性剥离
{
using type=_Ty;
my_refemove_reference()
{
int x=10;
_Ty y=x; //_Ty 此时的_Ty为int
}
};
template<class _Ty>
struct my_remove_reference<_Ty&&>
{
using type=_Ty; //typedef _Ty type;
my_refemove_reference()
{
int x=10;
_Ty y=x; //_Ty
}
};
int main()
{
my_remove_reference<int> i;
my_remove_reference<int&> ilr;
my_remove_reference<const int&> cilr;
my_remove_reference<int&&> rll;
my_remove_reference<int>::type x;
my_remove_reference<int &>::type y;
my_remove_reference<const int&>::type z=0; //剥离后采取的原始类型萃取
my_remove_reference<int &&> ::type w;
}
函数模板
template<class T>
const T& Max(const T& a,const T& b)
{
return a>b?a:b;
}
int main()
{
auto x=Max(12,23);
auto y=Max(12.23,34.45);
auto z=Max('a','b');
auto e=Max(12,23.34); //错误 无法编译通过 无法推演类型
return 0;
}
void func(int& a){}
void func(const int& b){}
void func(int && c){}
int main()
{
int a=10;
const int b=20;
func(a); //int & b; const int& c;
func(b);//const int& c;
func(20); //int &&d; const int& c;
}
template<class T>
void func(T&& x) //右值模板是一个未定义的模板 根据传入的实参确定 x并不是一个确定的 //右值引用
{
print(std::forward<T>(x)); //保证在被x具名后的右值在调用时,传入依然相当于右值
}
int main()
{
int a=10;
const int b=20;
func(a); //T int&, x int &
func(b); //T const int &,x const int &
func(20); //T int,x int &&
}
模板的特化现象
template<class T>
void fun(T a)
{
}
template<class T>
void fun<T*>(T* a)
{
}
template<>
void fun<char*>(char* a)
{
}
int main()
{
int a=10;
char ar[]="yhping";
fun(a);
fun(&a);
fun(ar);
}
template<class T>
T const & Min(T const & a,T const & b) //泛化版本
{
return a<b?a:b;
}
template<>
//const char* const &
Min<const char*>(const char* const & a,const char* const & b) //没有泛化版本 就没有特化 //版本 为了特化T const char* 特化T const & 保留
{
return strcmp(a,b)<0?a:b;
}
const char *Min(const char* pa,const char* pb); //Min模板函数的重载与特化不同