【问题标题】:Don't understand Template implementation of the JLospinoso books不懂 JLospinoso 书籍的模板实现
【发布时间】:2020-06-25 10:37:23
【问题描述】:

在 JLospinoso (c++ Crash Course) 中,第 10 章关于单元测试。Link to the book page

有这段代码(简体)

struct BrakeCommand {
    double time_to_collision_s;
};

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

---snips---

private:
    const T& publish;
}

叫什么

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

1 - 我完全不明白为什么会有这么多 {} [] ?模板一无所有...

2 - C++ 编译器 MSVC 引发此错误

“错误 C2955: 'AutoBrake': 使用类模板需要模板 参数列表”

为什么这里有模板?这个程序怎么编译?

非常感谢,

【问题讨论】:

  • 1. [](const BrakeCommand&amp;) {} 是所谓的 lambda 表达式。 2.这段代码需要C++17编译,确保你的编译器足够新,并且在设置中启用了C++17特性。
  • 非常感谢帮助像我这样的初学者,它有效;)

标签: c++ templates c++14


【解决方案1】:

{}[] 符号让您感到困惑,它是 lambda 定义的一部分,由 initializer_list 传递给 AutoBrake 构造函数。

让我们一步步看代码行

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

1 Lambda 将 BrakeCommand 作为参数并且什么都不做

[](const BrakeCommand&) {};

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);

现在让我们弄清楚模板是如何工作的。

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

由此声明模板参数 T,对于您的实例是一个函数。

所以预处理器从您的模板生成的代码看起来像

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

---snips---

private:
    const std::function& publish;
}

【讨论】:

    【解决方案2】:
    set(CMAKE_CXX_STANDARD 17)
    

    一切正常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多