【问题标题】:C++ Visual Studio error: Identifier cannot be implicitly captured because no default capture mode has been specifiedC++ Visual Studio 错误:无法隐式捕获标识符,因为未指定默认捕获模式
【发布时间】:2018-12-26 08:30:22
【问题描述】:

我正在尝试在此代码中提取 dir_entry.path() 的值,并希望将其复制到 compFileName 中。 问题是我不断收到错误“compFileName 无法被隐式捕获,因为没有指定默认捕获模式。

我知道这与 lambda 函数有关,但我对它们的经验为零。 关于我应该如何解决这个问题以实现我想要的任何建议?

#include <filesystem>
#include <algorithm>

namespace fs = std::filesystem;

void search(const fs::path& directory, const fs::path& file_name, string &compFileName)
{
    auto d = fs::recursive_directory_iterator(directory);

    auto found = std::find_if(d, end(d), [&file_name](const auto & dir_entry)
    {
        string t = dir_entry.path().filename().string();
        compFileName = t;
        return t == file_name;
    );

}

【问题讨论】:

    标签: c++ visual-studio lambda path filesystems


    【解决方案1】:

    除非你捕获它们,否则你不能在 lambda 中使用周围的变量。

    您使用了在周围范围内定义的compFileName,但它没有被列为捕获。

    简单修复:将&amp;compFileName 添加到您的捕获列表中:

    [&file_name, &compFileName](const auto & dir_entry) { ... }
    

    更简单:捕获所有使用的变量:

    [&](const auto & dir_entry) { ... }
    

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 1970-01-01
      • 2011-05-17
      • 2015-10-28
      • 2021-06-02
      • 1970-01-01
      • 2013-10-10
      • 2017-11-24
      • 2016-05-28
      相关资源
      最近更新 更多