Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

cout

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.

like image 373
H'H Avatar asked Sep 10 '26 17:09

H'H


2 Answers

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.

like image 110
Yakov Galka Avatar answered Sep 13 '26 10:09

Yakov Galka


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.

like image 23
Bathsheba Avatar answered Sep 13 '26 10:09

Bathsheba