利用C 模板,代替虚函数,实现类的静态多态性(加入性能测试部分) - woaidongmao - C 博客

来源:百度文库 编辑:神马文学网 时间:2024/04/28 23:31:56

利用C++模板,代替虚函数,实现类的静态多态性(加入性能测试部分)

    熟悉模板编程的朋友或许听到过这个技巧或者模式:Barton-Nackmann 技巧或者称 奇异循环模板模式(Curiously Recurring Template Prattern)。
     其实在 《c++ 编程语言》这本bible 书里,在模板那章提到过一个很奇妙的类的实现,用的就是这个技术。当时,我就被C++模板技术叹为观止。近期在学boost库时偶然碰到了这个技巧,同时在写一个类时引发了我的思考,这里就利用这个技巧来实现,静态多态函数(我自己发明的叫法,呵呵)。
 我们知道C++的多态函数会带来很多灵活性,但是不可避免的它是有运行时的性能损失的。 而c++的另一个强大特性就是模板了。模板给C++带来了,编译时的多态,通过模板元编程,C++可以实现类似C#,java的refection的特性。这里我就举来实现利用模板来代替虚函数。
 例子1:

#include
using namespace std;
 
class common_base
{
public:
  virtual void fun()=0;
};
class common_derive:public common_base
{
public:
  void fun()
  { cout<<"in common_derive fun()"<};
 
void main()
{
  common_base * pb = new common_derive;
  pb->fun();
}

  这是一个最普通的多态例子,下面看看一个比较有意思的例子:
例子2:

template
class class1
{
public:
    class1(T t):m_val(t){}
    virtual T getVal(){
        cout<<"in class1,val =="<< m_val <        return m_val;
    }
private:
    T m_val;
};

class derived: public class1
{
public:
    derived(int i):class1(i){}
    int getVal()
    {
        cout<<"in derived"<        return class1::getVal();
    }
};

template
class derived2: public class1
{
public:
    derived2(T val):class1(val){}
    T getVal()
    {
        cout<<"in derived2"<        return class1::getVal();
    }
};

void main()
{
    class1 * pbase = new derived(10);
    pbase->getVal();

    class1 * pb2 = new derived2(10);
    pb2->getVal();
}

这个例子我的用意是说明:模板类的虚函数多态,而且派生类可以有两种选择,一个实现为普通类,继承的是模板基类的特化类,一个就实现模板类(如 derived2)。很明显模板继承类有着普通类不可比拟的灵活性。

下面是这篇文章的重头戏了,也是本文的目的所在。
我们看到例子1,2都采用虚函数来实现多态,这个是一般选择,如何用模板来实现多态,而不是虚函数呢?
看这个例子:

template
class base
{
public:
    void print()
    {
        derive::print();
    }
    void m_print()
    {
        downcast()->derive::m_print();
    }
protected:
    inline derive * downcast()
    {
        return static_cast(this);
    };
    inline const derive * downcast()const
    {
        return static_cast(this);
    };
};

class der:public base
{
public:
    der(int foo):_foo(foo){}
    static void print()
    {
        cout<<"in der print"<    };
    void m_print()
    {
        cout<<"in der member fun m_print"<        cout<<"has member foo="<<_foo<    }
private:
    int _foo;
};

template
class der2:public base
{
public:
    static void print()
    {
        cout<<"in der2 print"<    };
    void m_print()
    {
        cout<<"in der2 member fun m_print"<    }
};

class tmpclass
{
public:
    void test()
    { cout<<"in test"<};

int main(int argc, char* argv[])
{
    //模板实现虚函数多态
    base * pb= new der(100);
    pb->print();
    pb->m_print();

    //动态继承
    der2 d2;
    d2.print();
    d2.m_print();
    d2.test();

    return 0;
}

哈哈,看class der是不是同样实现了多态??而且语义和虚函数一致。可以进一步提取downcast()部分到一个基类实现更普遍的写法。

后面我实现了一个动态继承的类der2,它同样提供了灵活的继承用法,可惜好像因编译器而定,在vc6环境下是不能通过编译的,而在g++下是ok的。

 下面我编写了一个性能测试例程来测试利用虚拟函数实现多态和模板实现多态的性能。代码如下

#include
using namespace std;
#include

class common_base
{
public:
    common_base(int iloop){_iloop=iloop;}
    virtual void virtual_fun()=0;
    void timesum_fun()
    {
        struct timeval begin,end;
        gettimeofday(&begin, NULL);
        for(int i=0;i<_iloop;i++)
            virtual_fun();
        gettimeofday(&end, NULL);
       cout<< "using time :" << end.tv_sec-begin.tv_sec +(end.tv_usec - begin.tv_usec)/1000000.0<<"  second"<    };
private:
    int _iloop;
};
class common_derive:public common_base
{
public:
    common_derive(int iloop):common_base(iloop){_foo=0;}
    void virtual_fun()
    {
        ++_foo;
        --_foo;
    }
private:
    int _foo;
};

template
class base
{
public:
    base(int iloop){_iloop=iloop;}
    void timesum_fun()
    {
        struct timeval begin,end;
        gettimeofday(&begin, NULL);
        for(int i=0;i<_iloop;i++)
            templ_fun();

        gettimeofday(&end, NULL);
       cout<< "using time :" << end.tv_sec-begin.tv_sec +(end.tv_usec - begin.tv_usec)/1000000.0<<"  second"<    }
    inline void templ_fun()
    {
        downcast()->derive::templ_fun();
    }
protected:
    inline derive * downcast()
    {
        return static_cast(this);
    };
    inline const derive * downcast()const
    {
        return static_cast(this);
    };
private:
    int _iloop;
};

class der:public base
{
public:
    der(int iloop):base(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 * ptempb= new der(loop);
  for(int i =3;i-->0;)
  {
      cout<<"virtual function test: looptime="<      pb->timesum_fun();
      cout<<"template function test: looptime="<      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

有点惊人是不是?这个差别就是因为虚函数是不可优化和内联的,而模板函数是可内联的,这个性能差异就很大,再次随着虚表的增大虚函数的调用是有性能退化的,而这点对于模板函数来说是没有的,因为在编译时,这一切都是静态了。不过客观的说,虚函数多态是C++语言内置的,在复杂度方面,应该首选虚函数,这里提供的这个方法只是作者在学习过程中的一个体会,模板的世界实在是太奇妙和高深了。