atl/wtl中运用的非虚函数多态

atl/wtl中运用的非虚函数多态

template <typename T>
class B1
{
public:
    void SayHi()
    {
        T *pT = static_cast<T*>(this);
        pT->PrintClassName();
    }

protected:
    void PrintClassName()
    {
        cout << "B1" << endl;
    }
};

class D1 : public B1<D1>
{
    // no overridden function at all
};

class D2 : public B1<D2>
{
public:
    void PrintClassName()
    {
        cout << "D2" << endl;
    }
};

void testAtlWtl()
{
    D1 d1;
    D2 d2;
    d1.SayHi();
    d2.SayHi();
}

这是一种运用模板机制实现c++中多态的一种方法,避免了虚函数的vtable的开销,是理解atl/wtl的最基本的原理。

原文地址:https://www.cnblogs.com/SunWentao/p/2198515.html