为什么 std::cin.getline 没有重载方法来获取 std::string?
我很好奇 cin.getline 和 全局 getline 函数位于不同的地方。
不简单地为 cin 定义所有这些函数签名的动机是什么:
//THESE TWO EXIST
istream& cin::getline (char* s, streamsize n );
istream& cin::getline (char* s, streamsize n, char delim );
//THESE TWO COULD EXIST
istream& cin::getline (string &s);
istream& cin::getline (string &s, char delim );
是因为可能想要添加其他类型并且他们不想将字符串与 cin 结合起来吗?
I'm curious about the technical reason for cin.getline and the global getline function being in different places.
What was the motivation for not simply defining all these function signatures for cin:
//THESE TWO EXIST
istream& cin::getline (char* s, streamsize n );
istream& cin::getline (char* s, streamsize n, char delim );
//THESE TWO COULD EXIST
istream& cin::getline (string &s);
istream& cin::getline (string &s, char delim );
Was it because other types may want to be added and they didn't want to marry the string to cin?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅我对类似问题的回答。这可能是 C++ 标准委员会的疏忽,但也可以用依赖性问题来解释。如果标准要求
标头中的std::string
函数重载,那么它将要求实现者#include
在
中。这是一个依赖项要求,这会进一步减慢编译任何需要
的内容——即使编译单元本身不需要std::string
。请注意,另一方面
标头具有引用std::basic_istream<>
和std::basic_ostream
的函数。 >
;但该标准还需要一个名为
的标头,它向前声明所有 IO 设施,使
标头依赖于编译时的快速
标头。相反的依赖关系编译起来会慢得多。See my answer for a similar question. It might be an oversight by the C++ Standard committee, but it can also be explained with dependency concerns. If the standard would require function overloads for
std::string
in the<iostream>
header then it would require implementers to#include<string>
in<iostream>
. That's a dependency requirement, which would further slow down compiling anything that requires<iostream>
-- even if a compilation unit doesn't itself needstd::string
.Do note that on the other hand the
<string>
header has functions that take a reference tostd::basic_istream<>
andstd::basic_ostream<>
; but the standard also requires a header named<iosfwd>
which forward-declares all IO facilities, making the<string>
header dependable on the compile-time fast<iosfwd>
header. A dependency the other way around would be much slower to compile.或多或少。 “他们”可能不希望 std::istream 依赖于 std::string 以任何方式,可能会最小化 耦合。
请注意, std::getline() 是在
中定义的;
模块。More or less. "They" probably didn't want to have std::istream depend on std::string in any way, probably to minimize coupling.
Note that std::getline() is defined in the
<string>
module.-Christopher
添加我在其他线程中找到的这篇文章,因为它似乎相关并接受答案。
-Christopher
Adding this post I found in that other thread because it seems relevant and accepting an answer.