I have question for printing text on the screen. I though that there is no valid "+" operator for out streaming text. why is this one valid:
std::cout << ("print this number " + boost::lexical_cast<std::string>(5) + ". " ) << std::endl;
although there is complie error for this:
std::cout << ("print this number " + "5" + ". " ) << std::endl;
error: invalid operands of types ‘const char [19]’ and ‘const char [2]’ to binary ‘operator+’
I use gcc 4.7.3 and C++03.
boost::lexical_cast returns an std::string which has operator +(const char *, const std::string&) and operator +(const std::string&, const char *) defined for it. So your code gets equivalent to:
std::cout << std::string("print this number 5. ") << std::endl;
There is no invocation of operator + with std::ostream arguments.
In your second line you try to add arrays of chars (const char [19] and const char [2] for example), which is an error by the language rules.
It's because the expression within the parentheses is evaluated first.
The type of boost::lexical_cast<std::string>(5) is std::string. That has overloaded + operators for const char* (on both sides), which return a std::string.
So the type of the expression in the parentheses is a std::string, and the stream has an overloaded << for it.
Finally "print this number " + "5" + ". " will not compile since + has no meaning for const char[] arguments, even if they decay to pointer types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With