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的最基本的原理。

相关文章:

  • 2021-11-26
  • 2022-12-23
  • 2021-11-23
  • 2021-04-03
  • 2021-05-27
  • 2021-09-04
猜你喜欢
  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2021-06-15
  • 2021-06-19
  • 2022-12-23
  • 2021-10-07
相关资源
相似解决方案