内容提炼
- decltype(expression) 关键字:得出experssion的类型
- typeid(variable) 返回variable的类型
- auto + + ->decltype{} 自动推演返回值
- 特化与偏特化
代码一(内置类型)typename
#include<iostream>
using namespace std;
template <typename T,typename U>
auto add(T a,U b)->decltype(a+b){
return a + b;
}
template <typename T,typename U>
auto add(T* a,U* b)->decltype(*a+*b){
return *a + *b;
}
template <>
int add(int a,int b){
return a+b;
}
int main(){
int a,b;
double m,n;
cout << "\033[33mplease input a(int),b(int),m(double),n(double) : \033[0m"<<endl;
cin >> a >> b >> m >> n;
cout << typeid(a+b).name() << endl;
cout << "\033[32madd("<<a<<","<<b<<") = "<<add(a,b)<<"\033[0m"<<endl;
cout << typeid(a+m).name() << endl;
cout << "\033[32madd("<<a<<","<<m<<") = "<<add(a,m)<<"\033[0m"<<endl;
cout << typeid(a+n).name() << endl;
cout << "\033[32madd("<<a<<","<<n<<") = "<<add(a,n)<<"\033[0m"<<endl;
int* x = &a,*y = &b;
cout << typeid(*x+*y).name() << endl;
cout << "\033[32madd("<<x<<","<<y<<") = "<<add(x,y)<<"\033[0m"<<endl;
return 0;
}
结果为:
please input a(int),b(int),m(double),n(double) :
3 5 7.8 3.4
i
add(3,5) = 8
d
add(3,7.8) = 10.8
d
add(3,3.4) = 6.4
i
add(0x7ffc93c9b080,0x7ffc93c9b084) = 8
代码二(自定义类型) class
#include "head.h"
using namespace std;
template <class T = double,class U = double>
class Test{
public:
Test(){
cout << "normal template" << endl;
}
};
template <class U>
class Test<int,U>{
public:
Test(){
cout << "partial specialization template" << endl;
}
};
template <>
class Test<int,int>{
public:
Test(){
cout << "specialization template" << endl;
}
};
int main(){
Test<int,int> t1;
Test<double,int> t2;
Test<int,double> t3;
Test<double,double> t4;
Test<> t5;
return 0;
}
结果为:
specialization template
normal template
partial specialization template
normal template
normal template
注意点
内置类型的模板参数是作为函数体的类型参数去使用,它的特化在于对参数的具象化。 自定义类型的模板的偏特化就需要在调用它是做显示声名。在定义该模板类时也需要对特化的类型做
|