简体   繁体   English

不懂 JLospinoso 书籍的模板实现

[英]Don't understand Template implementation of the JLospinoso books

In the JLospinoso (c++ Crash Course), chapter 10 about unit testing.在 JLospinoso (c++ Crash Course),第 10 章关于单元测试。 Link to the book page 链接到书页

There is this code (simplified)有这个代码(简化)

struct BrakeCommand {
    double time_to_collision_s;
};

template<typename T>
struct AutoBrake {
    AutoBrake(const T& publish) : publish{publish} {}

---snips---

private:
    const T& publish;
}

Which is called这就是所谓的

AutoBrake auto_brake{[](const BrakeCommand&) {}};

1 - I absolutely don't understand why there is this much {} []?? 1 - 我完全不明白为什么有这么多 {} []?? And nothing about the template...模板一无所有...

2 - C++ compiler MSVC raise this error 2 - C++ 编译器 MSVC 引发此错误

"error C2955: 'AutoBrake': use of class template requires template argument list" “错误 C2955:‘AutoBrake’:使用 class 模板需要模板参数列表”

Why is there a template here?为什么这里有模板? How to compile this program?如何编译这个程序?

Thanks a lot,非常感谢,

set(CMAKE_CXX_STANDARD 17)

And everything works fine !一切正常!

{}[] symbols which are confused you it's a part of the lambda definition passed by initializer_list to AutoBrake constructor. {}[] 符号让您感到困惑,它是由initializer_list传递给 AutoBrake 构造函数的lambda定义的一部分。

Let's go through the code line step by step让我们一步一步通过代码行 go

AutoBrake auto_brake{[](const BrakeCommand&) {}}; AutoBrake auto_brake{[](const BrakeCommand&) {}};

1 Lambda which takes BrakeCommand as an argument and does nothing 1 Lambda 将 BrakeCommand 作为参数并且什么都不做

[](const BrakeCommand&) {};

2 The constructor with initialized_list, lambda as an argument for it 2 以 initialized_list lambda 作为参数的构造函数

auto variable = [](const BrakeCommand&) {}; // to simplify understanding what is going on further
AutoBrake auto_brake{variable}; // it might be replaced by AutoBrake auto_brake(variable);

Now let's figure out how the template works.现在让我们弄清楚模板是如何工作的。

AutoBrake auto_brake{[](const BrakeCommand&) {}};

By this was declared that the template parameter T, for your instance is a function.由此声明模板参数 T,对于您的实例是 function。

So code generated by preprocessor from your template will look as因此,预处理器从您的模板生成的代码将如下所示

template<std::function>
struct AutoBrake {
    AutoBrake(const std::function& publish) : publish{publish} {}

---snips---

private:
    const std::function& publish;
}

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

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