简体   繁体   English

了解 C++ 使用模板和 class inheritance 编写的代码

[英]Understanding C++ Code written with templates and class inheritance

I came across the below piece of code in a header file.我在 header 文件中遇到了以下代码。

template <int x, template <typename T> class Car,
          typename DOC, typename COMMON,
          typename filter = imp::Filter>
class CurrentClass
    : public imp::base<
          x, Car, DOC,
          CurrentClass<x, Car, DOC, COMMON>, Filter> {
public:
  COMMON *common;
  CurrentClass(Connection &cnt, COMMON *common_)
      : imp::base<
            x, Car, DOC,
            CurrentClass<x, Car, DOC, COMMON>,
            Filter>(cnt),
       common(common_) {}
};

Can someone please explain the different parts of this code in terms of templates and class inheritance?有人可以根据模板和 class inheritance 解释此代码的不同部分吗?

According to my understanding CurrentClass inherits from the base class declared in imp class.据我了解, CurrentClass继承自在 imp class 中声明的基础 class。

Thanks谢谢

There is a lot of noise in this code and as mentioned, it is quite advanced, but google the points I note below.这段代码中有很多杂音,如前所述,它非常先进,但请搜索我在下面记下的要点。 There are several distinct things I can point out:我可以指出几件不同的事情:

1. 1.

template <int x, template <typename T> class Car,
      typename DOC, typename COMMON,
      typename filter = imp::Filter>

The "int x" part require that argument to be an integer “int x”部分要求该参数是 integer

The "template <typename T> class Car" is known as a template-template. “模板 <typename T> class Car”被称为模板模板。 It's essentially pulling the template-type out of a type.它本质上是将模板类型从类型中提取出来。 Example: std::vector<int> - the template-template is "int".示例:std::vector<int> - 模板模板是“int”。

Typename filter = imp::filter Is just a default template argument and is optional. typename filter = imp::filter 只是一个默认的模板参数并且是可选的。

2. You will notice that the class CurrentClass inherits from some base class imp::Base with some template arguments: x, car, doc. 2. 你会注意到 class CurrentClass 继承自一些基础 class imp::Base with some template arguments: x, car, doc。 You will then notice it passes itself + it's template arguments *to the base class.然后您会注意到它通过自身+ 它的模板 arguments * 到基础 class。 This is known as CRTP, and it's a way to create c++ virtuals, using templates.这称为 CRTP,它是一种使用模板创建 c++ 虚拟的方法。 Very powerful stuff.很强大的东西。

class CurrentClass
: public imp::base<
      x, Car, DOC,
      CurrentClass<x, Car, DOC, COMMON>, Filter> {

I've highlighted (with square brackets) the important bits of the CRTP below:我已经(用方括号)突出显示了下面 CRTP 的重要部分:

class CurrentClass
[: public imp::base<]
      x, Car, DOC,
      [CurrentClass<x, Car, DOC, COMMON>, Filter>] {

The constructor is just initialising the base class.构造函数只是初始化基础 class。 Which is normal code.这是正常的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM