//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);
}
学习笔记:几种注入方法
最新推荐文章于 2024-11-18 08:43:11 发布