您的位置:首页 > 其它

template-模板完全特化

2017-09-13 20:29 375 查看
类模板的定义与使用

#include <stdio.h>
#include <typeinfo.h>
template <class T1,class T2>
class A
{
T1 i;
T2 j;
public:
A(T1 t1,T2 t2) {i = t1; j = t2;}//内联函数
bool comp(){return i>j;}//内联函数
void print_Type();
};
//成员函数print_Type定义
template<class T1,class T2>
void A<T1,T2>::print_Type()
{
printf("i的类型是:%s\n",typeid(i).name()); //打印i的类型名
printf("j的类型是:%s\n",typeid(j).name()); //打印j的类型名
}

int main()
{
A<int,double> a(3,34.6);
if(a.comp() )
printf("i>j \n");
else
printf("i<j \n");
a.print_Type() ;
return 0;
}


函数模板的完全特化

#include <stdio.h>
template <class T>
void func(T a)
{
printf("hello \n");
}

template<> void func<int>(int a)//函数模板完全特化
{
printf("hello there\n");
}
int main()
{
func(2);
func('y');
return 0;
}
//输出:
//hello there
//hello


类模板的完全特化

#include <stdio.h>
template <class T>
class A
{
T i;
public:
A(T t){ i = t; printf("hello,%f\n", i); }
T compute()
{
return i*i;
}
};

template<> class A<int>//类模板A完全模板化
{
int i;
int k;
public:
A(int t){ i = t; printf("hello,%d\n",i); }
int compute(){ return i*i*i; }
};
int main()
{
A<double> dObj(2.5);
A<int> iObj(5);//打印hello
printf("%f\n", dObj.compute());//平方
printf("%d\n", iObj.compute());//立方
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息