学习笔记:几种注入方法
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); }
相关文章推荐
- cocos2d-x-3.1 vs 输出Log的几种方法 (coco2d-x 学习笔记三)
- APIDemo学习笔记——Android上几种简单的Animation使用方法(三)——3D Transition
- Spring学习笔记(10)-----------方法注入
- java学习笔记-Java实现几种常见排序方法
- Spring学习笔记二(Bean注入的几种方式)
- 学习笔记--linq链接数据库的几种方法
- Mini 容器学习笔记10——方法注入
- linux几种关机方法---学习笔记
- NUnit学习笔记4--单元测试和项目结合的几种方法
- Spring.Net对方法的注入(学习笔记三)
- struts2学习笔记---获得HttpServletResponse或HttpServletRequest对象的几种方法
- EIGRP区域注入静态路由的三种方法--CCNP学习笔记
- NUnit学习笔记4--单元测试和项目结合的几种方法
- NUnit学习笔记4--单元测试和项目结合的几种方法(摘录)
- APIDemo学习笔记——Android上几种简单的Animation使用方法(二)
- NUnit学习笔记4--单元测试和项目结合的几种方法
- SharePoint【学习笔记】-- 自定义 SharePoint 2010 的配色主题的几种方法
- cocos2d-x学习笔记(二)序列帧动画实现的几种方法
- JavaScript学习笔记之浅析几种创建对象的方法
- Open CV 学习笔记:访问图像中像素的几种方法