Since my shifting from C to C++ I have a question on STL’s formatting output. How ostreams tell one basic type from another?
In C with its printf and formatting strings it was pretty straightforward, but in C++ ostreams somehow distinguish basic types automatically. It puzzles me.
For example, in the following code,
int i;
float f;
std::cout << i << std::endl;
std::cout << f << std::endl;
how cout “knows” that i is an int and f is a float?
The compiler converts the operators to function calls. So that
becomes
Somewhere buried deep in the bowels of the standard library headers there are function declarations (functionally equivalent to):
That is,
operator<<is overloaded. When the function call is made, the compiler chooses the function overload which is the best match to the arguments passed in.In the case of
std::cout << i, theintoverload is chosen. In the case ofstd::cout<<d, thedoubleoverload is chosen.You can see function overloading in action fairly simply with a contrived example:
Producing the output:
Try it for yourself: http://ideone.com/grlZl.
Edit: As Jesse Good points out, the functions in question are member functions. So really we have:
becomes
And in the headers there are declarations (equivalent to):
The same basic idea holds, however.