C++模板技术实例(2) 静态多态

来源:互联网 发布:华为进入一组端口 编辑:程序博客网 时间:2024/05/21 22:52

  面向对象技术在当今的软件开发中占据有举足轻重的地位,大大提高了代码复用性和可维护性,然而,有利必有弊,C++的多态,实际上用的是一个look-up table,运行时动态查找函数入口点,显然,会有一定的性能损失,当实际运行的代码完成的功能是一个简单计算的时候,性能损失更是明显。

  这里我用C++模板的技术,完成一个静态的多态(Static Polymorphism):

  运行时多态:

  1. // 一般情况下,我们采用的是运行时多态,代码大致是这样的
  2. class Base
  3. {
  4. public:
  5.     virtual void method() { std::cout << "Base"; }
  6. };
  7. class Derived : public Base
  8. {
  9. public:
  10.     virtual void method() { std::cout << "Derived"; }
  11. };
  12. int main()
  13. {
  14.     Base *pBase = new Derived;
  15.     pBase->method(); //outputs "Derived"
  16.     delete pBase;
  17.     return 0;
  18. }

    静态多态(Static Polymorphism):

  1. // Static Polymorphism
  2. template <class Derived>
  3. struct base
  4. {
  5.     void interface()
  6.     {
  7.         // ...
  8.                   // static_case是编译期间完成类型映射,又可以减少运行时性能损失
  9.         static_cast<Derived*>(this)->method();
  10.         // ...
  11.     }
  12.          virtual ~base(){} // 为什么要用virtual,不用多解释了吧:)
  13. };
  14. struct derived : base<derived>
  15. {
  16.     void method() { std::cout << "Derived";}
  17. };
  18. int main()
  19. {
  20.          // 把子类作为模板参数,实例化一个模板
  21.     base<derived> *pBase = new derived();
  22.          // 调用基类的代理方法,注意,这个方法是inline的,不会有函数调用性能损失
  23.     pBase->interface(); //outputs "Derived"
  24.     delete pBase;
  25.     return 0;
  26. }
原创粉丝点击