子类B继承自模板类A< B>. [英] Subclass B Inherits From a Template Class A<B>

查看:64
本文介绍了子类B继承自模板类A< B>.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近偶然发现了看起来像这样的代码,但我对此一无所知:

I recently stumbled upon code that looks like this and I can't wrap my head around it:

template<typename T>
class A
{
}

class B: A<B>
{
}


所以我的一般问题是:


So my general questions are:

  • 为什么没有给出编译错误?具体来说,如果尚未定义B,则类B如何从模板类A<B>继承?
  • 何时需要这种结构?
  • Why does this not give a compile error? Specifically how can class B inherit from the template class A<B>, if B hasn't even been defined yet?
  • When would this structure ever be necessary?

推荐答案

功能之一:此模板模式可以帮助您避免使用vtable.这称为静态多态性"- http://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern

One of the features: this template pattern can help you to avoid vtable usage. This called "Static polymorphism" - http://en.m.wikipedia.org/wiki/Curiously_recurring_template_pattern

假设您具有以下代码结构:

Suppose you have this code structure:

class Item {
public:
    virtual void func() = 0;
}

class A : public Item {
// …
}

class B : public Item {
// …
}

Item *item = new A();
item->func();

它可以替换为:

template<typename T>
class Item {
public:
    void func() {
        T::func();
    }
}

class A : public Item<A> {
// …
}

class B : public Item<B> {
// …
}

Item<A> *item = new A();
item->func();

这样可以避免虚拟函数调用.可以这样做以提高性能...

This way you can avoid virtual function call. This can be done for some performance improvement...

这篇关于子类B继承自模板类A&lt; B&gt;.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆