gpt4 book ai didi

c++ - std::istream 类型是 EqualityComparable 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:26 25 4
gpt4 key购买 nike

我的问题会有一个 bool 值答案:是或否。不管是哪一个,有人能解释一下下面的代码是如何被 GNU-g++ 4.9.2 和 clang 3.5 编译的,而 GNU-g++ 5.1.1 不再接受它,声称没有匹配的 operator== ?

以及如何更改它,对于最后一个编译器,为了获得相同的结果,即让 operator>> 能够以如此简单的方式区分,是否它是由标准输入流或其他东西调用的?

  # include <iostream>
# include <fstream>

struct S {};

std::istream& operator >> (std::istream& i, S& s)
{
if(i == std::cin) std::clog << "this is standard input\n";
else std::clog << "this is some other input stream\n";

return i;
}

int main(int narg, const char ** args)
{
S s;
std :: cin >> s;
std::ifstream inp(args[1]);
inp >> s;
}
// to be executed with the name of an existing
// disk file on the command line....

最佳答案

没有。没有对 std::istream 对象进行操作的 operator==

您能够比较两个 std::istreamstd::istream 的转换函数导致的不幸结果,特别是 operator void* .在表达式 i == std::cin 中,istd::cin 都被隐式转换为 void*,然后比较结果值。这其实意义不大。这个转换函数在 C++11 中被移除了(取而代之的是一个 explicit 转换函数,在这种情况下不会被调用),所以如果启用 C++11 模式,代码将不编译。

如前所述here ,如果你想检查引用i是否引用std::cin,你可以使用&i == &std::cin.

关于c++ - std::istream 类型是 EqualityComparable 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com