C++ - 没有运算符“<<"匹配这些操作数 directory_iterator() [英] C++ - no operator &quot;&lt;&lt;&quot; matches these operands directory_iterator()

查看:43
本文介绍了C++ - 没有运算符“<<"匹配这些操作数 directory_iterator()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我复制了 directory_iterator 页面上的示例代码,所以这就是我所拥有的:

#include "pch.h"//为了视觉工作室的利益#include <fstream>#include #include <文件系统>命名空间 fs = std::filesystem;int main(){fs::create_directories("sandbox/a/b");std::ofstream("沙盒/file1.txt");std::ofstream("沙箱/file2.txt");for (auto& p : fs::directory_iterator("sandbox"))std::cout <<p<<'\n';//这一行在第一个 '<<'是错误发生的地方fs::remove_all("沙盒");返回0;//由我包含}

错误信息是:

Severity Code 描述 Project File Line Suppression State错误(活动)E0349 无操作符<<"匹配这些操作数

由于我是 C++ 的新手,我可能弄错了,但我对错误的理解基本上是 p 在我的情况下是无法打印到控制台的东西cout.

如果我直接在页面上运行该示例,则该示例有效,因此它没有任何问题,这也是我不期望的.那么问题来了,为什么我会看到这个错误?

我使用最新版本的 Visual Studio 和 C++ 2017.

解决方案

directory_entry 不直接支持流;它通过 pathoperator<< 加上隐式转换到 const std::filesystem::path & 来获取它.>

由于 LWG 问题 29893065path的操作符已经变成了隐藏的朋友,不能再用来流式传输可转换为path,例如 directory_entry.

解决方法是直接请求 .path() 而不是依赖于隐式转换.我已经修复了 cppreference 示例.

<小时>

与 LWG 核实后,此更改似乎是无意的.我已提交LWG 3171.

I've copied the example code on the directory_iterator page, so this is what I have:

#include "pch.h" //for visual studios benefit
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    fs::create_directories("sandbox/a/b");
    std::ofstream("sandbox/file1.txt");
    std::ofstream("sandbox/file2.txt");
    for (auto& p : fs::directory_iterator("sandbox"))
        std::cout << p << '\n'; //this line on the first '<<' is where the error occurs
    fs::remove_all("sandbox");
    return 0; //included by me
}

And the error message is:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0349   no operator "<<" matches these operands 

As I'm new to C++ I might have gotten things wrong, but my understanding of the error is basically that p in my case is something which can't be printed out to the console using cout.

The example works if I run it directly on the page so there isn't something wrong with it, which I wouldn't expect either. So question is, why am I seeing this error?

I use the latest version of Visual Studio, along with C++ 2017.

解决方案

directory_entry doesn't have streaming support directly; it gets it via path's operator<< plus an implicit conversion to const std::filesystem::path &.

As a result of LWG issues 2989 and 3065, path's operators have been made into hidden friends, and can no longer be used to stream things convertible to a path, such as a directory_entry.

The fix is to ask for .path() directly rather than depend on the implicit conversion. I've fixed the cppreference example.


After checking with LWG, this change appears to be unintended. I've filed LWG 3171.

这篇关于C++ - 没有运算符“<<"匹配这些操作数 directory_iterator()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆