H'H H'H - 9 months ago 32
C++ Question

validity of "+" operator while using "<<"

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.