std::cout doen't like std::endl and string in conditional-if

末鹿安然 提交于 2019-12-04 05:53:27

问题


main.cpp: In function ‘void PrintVector(std::vector<std::__cxx11::basic_string<char> >&, bool)’:
main.cpp:16:41: error: overloaded function with no contextual type information
  std::cout << ((newline)? (std::endl) : "");
                                         ^~

Why std::cout doen't like std::endl and string in conditional-if?


回答1:


std::endl is a stream manipulator. It's a function. It does not have a common type with "". So they cannot be the two types of a conditional expression. Since the common type is the type of the whole expression.

You probably don't even need everything std::endl does besides adding a new line, so just replace it with "\n" to print a new-line. That way the common type may be deduced to const char* after all the usual conversions are performed on the operands.




回答2:


I changed it to:

std::cout << (newline? "\n" : "") << std::flush;

It is not possible to write it with ' (would be faster):

std::cout << (newline? '\n' : '') << std::flush;

because '' is empty and leads to "error: empty character constant".

The solution with the conditional-if is so complex that one should prefer the following:

if (newline) std::cout << std::endl;


来源:https://stackoverflow.com/questions/47854103/stdcout-doent-like-stdendl-and-string-in-conditional-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!