小编bec*_*cca的帖子

C++ 令人困惑的闭包捕获 [v] 与 [v = v]

在下面的代码中,编译器有时似乎更喜欢调用模板化构造函数,并且在复制构造函数应该没问题时无法编译。行为似乎会根据值是否被捕获为 [v] 或 [v = v] 而改变,我认为这些应该是完全相同的事情。我缺少什么?

我正在使用 gcc 11.2.0 并使用“g++ file.cpp -std=C++17”进行编译

#include <functional>
#include <iostream>
#include <string>

using namespace std;

template <class T>
struct record {
  explicit record(const T& v) : value(v) {}

  record(const record& other) = default;
  record(record&& other) = default;

  template <class U>
  record(U&& v) : value(forward<U>(v)) {} // Removing out this constructor fixes print1

  string value;
};

void call(const std::function<void()>& func) { func(); }

void print1(const record<string>& v) {
  call([v]() { cout << v.value << …
Run Code Online (Sandbox Code Playgroud)

c++ c++17

16
推荐指数
2
解决办法
926
查看次数

标签 统计

c++ ×1

c++17 ×1