为什么我可以重载 istream 的运算符>>用于字符串?

Why can I overload istream's operator>> for strings?

本文关键字:gt 字符串 用于 运算符 我可以 重载 istream 为什么      更新时间:2023-10-16

假设我希望operator>>istream中提取整行而不是空格分隔的单词。我很惊讶地看到,这虽然可怕,但实际上有效:

#include <iostream>
#include <string>
namespace std {
  istream &operator>>(istream &is, string &str) {
    getline(is, str);
  }
}
int main() {
  std::string line;
  std::cin >> line;
  std::cout << "Read: '" << line << "'n";
}

如果我在 stdin(标准)中键入多个单词,它实际上会调用我的运算符并读取整行。

我希望operator>>的定义与官方定义冲突,从而产生链接错误。为什么不呢?


编辑:我认为也许真正的operator>>是一个模板,非模板函数优先,但这仍然有效:

namespace std {
  template<typename charT>
  basic_istream<charT> &operator>>(basic_istream<charT> &is, basic_string<charT> &s) {
    getline(is, s);
  }
}

碰巧有效,因为官方模板不太具体(还有其他模板参数)。

然而,这是未定义的行为™。您只能为自己的类型提供标准库符号的重载。如果您遇到另一个将定义额外重载的标准库(可能),它将停止工作,您将不知道为什么。