使用模板将可能的运行时错误变为编译时错误

 

#include  < iostream >
using   namespace  std;

// 当CD不使用模板参数时填充此类
class  CNull
{
public:
    
static CNull* instance()
    
{
        
return &m_oCNull;
    }

private:
    
static CNull m_oCNull;
}
;

CNull CNull::m_oCNull;

class  CA
{
public:
    
static CA* instance()
    
{
        
return &m_oCA;
    }

    
void f1()
    
{
        
//do something...
        cout << "CA.f1()" << endl;
    }


private:
    
static CA m_oCA;
}
;

CA CA::m_oCA;

class  CB
{
public:
    
static CB* instance()
    
{
        
return &m_oCB;
    }

    
void f2()
    
{
        
//do something...
        cout << "CB.f2()" << endl;
    }


private:
    
static CB m_oCB;
}
;

CB CB::m_oCB;

class  CC
{

}
;

// 此类有两个模板参数
template  < class  T1,  class  T2 >
class  CD
{
public:
    CD()
    
{
        m_pT1 
= T1::instance();
        m_pT2 
= T2::instance();
    }


    
~CD()
    
{
        m_pT1 
= NULL;
        m_pT2 
= NULL;
    }


    T1
* getT1()
    
{
        
return m_pT1;
    }


    T2
* getT2()
    
{
        
return m_pT2;
    }


private:
    T1
* m_pT1;
    T2
* m_pT2;
}
;


int  main()
{
    
//当两个模板参数都被使用时
    CD<CA, CB> d;
    d.getT1()
->f1();    //因为CA有函数f1,所以成功
    d.getT2()->f2();    //因为CB有函数f2,所以成功

    
//当只有一个模板参数被使用时,将第二个参数设为CNull
    CD<CA, CNull> d2;
    d2.getT1()
->f1();    //因为CA有函数f1,所以成功
    d2.getT2()->f2();    //因为CNull没有函数f2,所以编译时出错

    
//当错误的使用了不带instance函数的类CC时,会编译时出错
    CD<CC, CC> d3;

    
return 0;   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值