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.

 

 

转载于:https://www.cnblogs.com/walfud/articles/2690231.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值