学习笔记:几种注入方法

//member template

class Integer{
public:
    template <int N> void multiple();
private:
    int i_;
};

template <> void Integer::multiple<-1>(){ i_=0; }
template <> void Integer::multiple<1>(){}
template <> void Integer::multiple<2>(){ i_<< 1; }
template <> void Integer::multiple<3>(){ i_*=3 ; }

void main(){
    Integer i;
    i.multiple<2>(); //ok. and fast.
    i.multiple<4>(); //compile error
}

//crtp idiom.

template<class H>
class Arithmetic{   //interface
public:
    H& operator++()
    {
        H* ph = static_cast<H*>(this);
        ph->inc(1);
        return *ph;
    }

    H& operator+=(int n)
    {
        H* ph = static_cast<H*>(this);
        ph->inc(n);
        return *ph;
    }

    H operator++(int n)
    {
        H* ph = static_cast<H*>(this);
        H tmp = *ph;
        ph->inc(n);
        return tmp;
    }

    friend H operator+(const H& lhs, const H& rhs){
        lhs.m_;
        return H(0);
    }
};

class Integer : public Arithmetic< Integer >
{
public:
    Integer(T a):m_(a){}
    Integer(const Integer& t):m_(t.m_){}
    void inc(int n){ //depended implementation. flexed changed.
        m_+=n;
    }
private:
    int m_;
};

int main(){
    
    Integer a(10);
    ++a;
    a++;
    a+=3;
    Integer b(10);

    Integer c = a + b;
    return 0;
}

//C++11. friend in template 

template<class T>
class Integer{
    friend T;
    int m_;
};

class Test{
public:
    void inc( Integer<Test>& t, int n){
        t.m_+=n;
    }
};

int main(){
    Integer<Test> i;
    Test t;
    t.inc(i,3);
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值