使用模板的动态多态性行为

Behaviour of dynamic polymorphism using templates?

本文关键字:多态 多态性 性行为 动态      更新时间:2023-10-16

几年前,在一次面试中,有人向我展示了一些看起来很可怕的代码,这些代码的行为与动态多态性相同,但使用了模板。我指的不是模板的正常用法。

如何使用模板来实现相当于运行时多态性的行为?

更新:我认为它与这个有关:

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern Static_polymorphism

使用奇怪循环模板模式(CRTP),您可以实现类似于编译时多态性的功能。下面是一个简单的例子:

template<typename DERIVED>
struct base
{
public:
    void f() const
    {
        static_cast<DERIVED&>( *this ).f_();
    }
};
struct derived1 : public base<derived1>
{
    void f_() const
    {
        std::cout << "Derived1!n";
    }
};
struct derived2 : public base<derived2>
{
    void f_() const
    {
        std::cout << "Derived2!n";
    }
};
template<typename DERIVED>
void call( const base<DERIVED>& e )
{
    e.f(); //compile-time resolved (Possibly inlined) polymorphic call here
}
int main()
{
    derived1 d1;
    derived2 d2;
    call( d1 );
    call( d2 );
 }

以上代码输出:

derived1 !
derived2 !