template-模板完全特化

  • 类模板的定义与使用
#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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值