面向对象技术在当今的软件开发中占据有举足轻重的地位,大大提高了代码复用性和可维护性,然而,有利必有弊,C++的多态,实际上用的是一个look-up table,运行时动态查找函数入口点,显然,会有一定的性能损失,当实际运行的代码完成的功能是一个简单计算的时候,性能损失更是明显。
这里我用C++模板的技术,完成一个静态的多态(Static Polymorphism):
运行时多态:
- // 一般情况下,我们采用的是运行时多态,代码大致是这样的
- class Base
- {
- public:
- virtual void method() { std::cout << "Base"; }
- };
- class Derived : public Base
- {
- public:
- virtual void method() { std::cout << "Derived"; }
- };
- int main()
- {
- Base *pBase = new Derived;
- pBase->method(); //outputs "Derived"
- delete pBase;
- return 0;
- }
静态多态(Static Polymorphism):
- // Static Polymorphism
- template <class Derived>
- struct base
- {
- void interface()
- {
- // ...
- // static_case是编译期间完成类型映射,又可以减少运行时性能损失
- static_cast<Derived*>(this)->method();
- // ...
- }
- virtual ~base(){} // 为什么要用virtual,不用多解释了吧:)
- };
- struct derived : base<derived>
- {
- void method() { std::cout << "Derived";}
- };
- int main()
- {
- // 把子类作为模板参数,实例化一个模板
- base<derived> *pBase = new derived();
- // 调用基类的代理方法,注意,这个方法是inline的,不会有函数调用性能损失
- pBase->interface(); //outputs "Derived"
- delete pBase;
- return 0;
- }