简体   繁体   English

将std :: endl传递给std :: operator <

[英]pass std::endl to std::operator <<

In this Stack Overflow answer it says that std::cout << "Hello World!" << std::endl; 在这个Stack Overflow答案中,它说的是std::cout << "Hello World!" << std::endl; std::cout << "Hello World!" << std::endl; is the same as 是相同的

std::operator<<(std::operator<<(std::cout, "Hello World!"), std::endl);

But when I compile the above line code, it doesn't compile! 但是当我编译上面的代码时,它不会编译! Then after trying something else I found that the reason it doesn't compile is because of std::endl , if I replace std::endl by "\\n" then it works. 然后,在尝试了其他方法之后,我发现它无法编译的原因是由于std::endl ,如果我将std::endl替换为"\\n"则它可以工作。 But why you can not pass std::endl to std::operator<< ? 但是为什么不能将std::endl传递给std::operator<<

Or more simply, isn't std::cout<<std::endl; 更简单地说,不是std::cout<<std::endl; the same as std::operator<<(std::cout, std::endl); std::operator<<(std::cout, std::endl); ?

EDIT 编辑

When compile with icpc test.cpp , the error message is error: no instance of overloaded function "std::operator<<" matches the argument list argument types are: (std::ostream, <unknown-type>) std::operator<<(std::cout, std::endl); 当使用icpc test.cpp编译时,错误消息为error: no instance of overloaded function "std::operator<<" matches the argument list argument types are: (std::ostream, <unknown-type>) std::operator<<(std::cout, std::endl);

and g++ test.cpp gives much much longer error message. g++ test.cpp给出了更长的错误消息。

It's because the answer there is a bit wrong. 这是因为答案有点错误。 std::endl is a manipulator function, there is no overload for them in definitions of standalone operator<< of ostream . std::endl是一个操纵器函数,在ostream的独立operator<<的定义中没有重载。 It is a member function of basic_ostream . 它是basic_ostream的成员函数。

In other word, the presented invocation is wrong. 换句话说,提出的调用是错误的。 It should be one of the following: 它应该是以下之一:

#include <iostream>
int main() {
    std::endl(std::operator<<(std::cout, "Hello World!"));
    std::operator<<(std::cout, "Hello World!").operator<<(std::endl);

    //of course if you pass new line as a supported type it works
    std::operator<<(std::operator<<(std::cout, "Hello World!"), '\n');
    std::operator<<(std::operator<<(std::cout, "Hello World!"), "\n");
    std::operator<<(std::operator<<(std::cout, "Hello World!"), string("\n"));
    return 0;
}

Live examples. 现场例子。

Well, some people do say that stream library does not have the prettiest design in the standard. 好吧,有人确实说过,流库在标准中没有最漂亮的设计。

I dont know about this topic, but i think these 2 questions and answers are somewhat related to your question and might help you figure out a solution 我不知道这个话题,但是我认为这2个问题和答案与您的问题有些相关,可能会帮助您找到解决方案

operator << must take exactly one argument 运算符<<必须正好接受一个参数

Does std::cout have a return value? std :: cout是否有返回值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM