问题
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