学习笔记:几种注入方法

来源:互联网 发布:开淘宝描述店铺怎么写 编辑:程序博客网 时间:2024/05/16 11:18
//member templateclass 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{   //interfacepublic:    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);}

0 0
原创粉丝点击