以下声明是什么意思? [英] What does the following declarations mean?

查看:102
本文介绍了以下声明是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类B继承自类A,但我不明白为什么类B以这种方式声明。

I have one class B which inherited from class A, but I dont understand why class B declares in this way.

class B : public A <B>
{
public:
    ...
};

template <class T>
class A
{
public:
        ....
}


推荐答案

正如PeterT所指出的,这是好奇地重复模板模式(CRTP)
这是一种在C ++中实现静态多态性的方法,因为基类 A 具有子类 B 及其(内部)类型和状态。

As already pointed out by PeterT, this is the curiously recurring template pattern (CRTP). It is a way to implement static polymorphism in C++ as the base class A has knowledge about the subclass B and its (internal) types and states.

例如, A 中的逻辑可以返回正确类型的对象, 。 CRTP允许将该逻辑移动到基类,其中动态多态性将需要派生类中的虚函数来处理适合 B 的正确类型。

For instance, the logic in A can return objects of the right type which would not be possible with dynamic polymorphism. CRTP allows to move that logic to the base class where dynamic polymorphism would require virtual functions within the derived class to deal with the right type appropriate to B.

此处提供了更详细的说明。

A more detailed explanation is given here.

这篇关于以下声明是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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