您的位置:首页 > 其它

学习笔记:几种注入方法

2014-09-17 16:12 375 查看
//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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: