Recurring Template Idiom

#include <iostream>
using namespace std;

class Base
{
public:
    void foo();
};

class Derive : public Base
{
public:
    void foo() const
    {
        cout <<"Derive." <<endl;
    }
};

void Base::foo()                // Defination of 'Base::foo' must be 
{
    static_cast<Derive *>(this)->foo();
}

int _tmain(int argc, _TCHAR* argv[])
{
    Derive d;

    Base *p = &d;
    p->foo();                    // Simulate 'virtual function'.

    return 0;
}

  We can use 'static_cast<Derive *>' to use funtion in derived class, but if we have another derived class? 'class Derive2 : public Base; class Derive3 : public Base...'. In that way, we have to distinct derived class and cast 'this' pointer to corresponding derived class. With the increasement of derived class, our code is going to be unmaintainable, which is terrible!

 

Solution:

template <typename T>
class Base
{
public:
    void foo()
    {
        static_cast<T *>(this)->foo();     // Solve the problem!
    }
};

class Derive : public Base<Derive>         // Recurring Template Idiom.
{
public:
    void foo()
    {
        cout <<"Derive." <<endl;
    }
};

  This way seems more elegant. As you see, we use template to generate code automatically.

 

 

posted @ 2012-09-18 11:03  walfud  阅读(164)  评论(0编辑  收藏  举报