几年前,在一次采访中,我看到了一些看上去很恐怖的代码,它的行为与动态多态性相同,但是使用了模板。我不是指模板的正常使用。
模板如何用于实现与运行时多态等效的行为?
更新:我认为这与此有关:
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 );
}
上面的代码输出:
派生1!
派生2!