class der:public base<der> { public: der(int foo):_foo(foo){} static void print() { cout<<"in der print"<<endl; }; void m_print() { cout<<"in der member fun m_print"<<endl; cout<<"has member foo="<<_foo<<endl; } private: int _foo; };
template<class base> class der2:public base { public: static void print() { cout<<"in der2 print"<<endl; }; void m_print() { cout<<"in der2 member fun m_print"<<endl; } };
class tmpclass { public: void test() { cout<<"in test"<<endl;} };
int main(int argc, char* argv[]) { //模板实现虚函数多态 base<der> * pb= new der(100); pb->print(); pb->m_print();
class der:public base<der> { public: der(int iloop):base<der>(iloop){_foo=0;} inline void templ_fun() { ++_foo; --_foo; } private: int _foo; };
int main() { int loop=1000*1000*100; common_base * pb = new common_derive(loop); base<der> * ptempb= new der(loop); for(int i =3;i-->0;) { cout<<"virtual function test: looptime="<<loop<<endl; pb->timesum_fun(); cout<<"template function test: looptime="<<loop<<endl; ptempb->timesum_fun(); } delete pb; delete ptempb; return 0; }
我编译了两个版本一个优化版本一个未优化版本,运行测试结果让我有点意外:
这是未优化版本的,结果显示这两种方法不相上下,虚函数还略优,~O~
./cmp_test virtual function test: looptime=100000000 using time :1.03824 second template function test: looptime=100000000 using time :1.63043 second virtual function test: looptime=100000000 using time :1.03768 second template function test: looptime=100000000 using time :1.62773 second virtual function test: looptime=100000000 using time :1.63104 second
运行优化版本,性能优势一下体现出来了,模板实现是虚函数的十倍:
./cmp_test_optimize virtual function test: looptime=100000000 using time :0.615542 second template function test: looptime=100000000 using time :0.055584 second virtual function test: looptime=100000000 using time :0.624778 second template function test: looptime=100000000 using time :0.057419 second virtual function test: looptime=100000000 using time :0.624977 second template function test: looptime=100000000 using time :0.059442 second