C++ manipulators? - c++

How does the c++ standard define the recognition of manipulators or just manipulators in general?
For example:
using namespace std;
ostream& hello_manip(ostream& os){
os<<"Hello there, fine fellow!"; return os;
}
int main(){
cout<<hello_manip;
}
The code cout << hello_manip would seem to be translated into operator<<( cout, hello_manip ) or cout.operator<<(hello_manip), but instead it takes up the form of hello_manip( cout ).

There's an overload of operator<< that accepts a function pointer and invokes it. No magic involved.
Processing of simple manipulators such as yours is described in section 27.7.3.6.3 of the Standard.
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& (*pf) basic_ostream<charT,traits>&))
Effects: None. Does not behave as a formatted output function (as described in 27.7.3.6.1).
Returns: pf(*this).
basic_ostream<charT,traits>& operator<<(basic_ios<charT,traits>& (*pf) basic_ios<charT,traits>&))
Effects: Calls pf(*this). This inserter does not behave as a formatted output function (as described in 27.7.3.6.1).
Returns: *this.
basic_ostream<charT,traits>& operator<<(ios_base& (*pf)(ios_base&))
Effects: Calls pf(*this). This inserter does not behave as a formatted output function (as described in 27.7.3.6.1).
Returns: *this.
More complex manipulators (which accept parameters and carry state) are implemented by returning functor objects, which have their own operator<< overloads.

Related

overload operator<< in google c++ style

I try to overload operator<< for my class so that it print member when I do
std::cout << obj;
I see that the way to do this is
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
What are the basic rules and idioms for operator overloading?
However, I try to make my code conforms to Google C++ style guide
https://google.github.io/styleguide/cppguide.html#Reference_Arguments
It says that passing the reference without const is not allowed except for the case that it is needed by convention such as swap(). Is this overloading operator<< in the same category as swap()? or there is a way to do something like
std::ostream& operator<<(std::ostream* os, const T& obj)
^
? or something that does not take non-const reference as the input.
If so, please teach me how to do that. Thank you.
It says that passing the reference without const is not allowed except for the case that it is needed by convention
Well, the stream is conventionally passed as a non-const reference into the stream insertion and extraction operators, so it would appear that the rule has allowed an exception for you. As such, defining the suggested overload should be conforming to the rule despite accepting a non-const reference argument.
That said, I'm not an authority on what Google would consider as convention. If you work for Google, you should know whom to ask; If you don't then you don't need to get stressed over their style.

Calling a function which manipulates the ostream doesn't require parentheses. C++

I know a function cannot be called without a parentheses, however, let's say I have this piece of source code:
#include<iostream>
using namespace std;
ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}
int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}
/// Output:
/// 1.11235e+002
/// 111.123
There isn't any overloading for the left-shift operator, yet when I call the test(ostream& os) function in the cout at the main function, it does not require any parentheses. My question is why?
There isn't any overloading for the left-shift operator
Yes there is, it's defined in <ostream>.
It uses exactly the same technique that allows endl and scientific to work. There is an overload taking a function pointer, which calls the function pointer when it's written to a stream.
basic_ostream has these member functions which accept function pointers:
// 27.7.3.6 Formatted output:
basic_ostream<charT,traits>&
operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(basic_ios<charT,traits>& (*pf)(basic_ios<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(ios_base& (*pf)(ios_base&))
{ return pf(*this); }
cout << test uses the first of those overloads, which is equivalent to cout.operator<<(&test), which does return test(*this); so the call happens inside the overloaded operator<<.
ostream has overload of operator << for this case:
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Calls func(*this);. These overloads are used to implement output I/O
manipulators such as std::endl.

Overloading the stream insertion (<<) operator?

When we overload the stream insertion operator to work on user defined objects, we usually define it as a global friend function as follows:
ostream& operator << (ostream& out, const MyClass& x) {
// Do something
return out;
}
My question is, I believe the object cout (which is a global object) is passed as the first argument to this function. But, why? It's a global function, so it is accessible in this function anyway, why pass it as an argument. In other words, why not do the following:
ostream& operator << (const MyClass& x) {
// Do something
return cout;
}
There are two reasons.
One is semantic: the first argument need not be std::cout. It can be any std::ostream, be it std::cerr, a std::ofstream, a std::ostringstream, etc.
The second is syntactic: << necessarily takes two arguments, and there's no way to write an overload without two arguments (though the first argument can be a this argument).

C++ stringstream inline

I would like to use std::stringstream to create formatted strings, but use the class inline so I don't have stringstream local variables flying around. What I mean is this:
#include <iostream>
#include <ostream>
#include <string>
#include <sstream>
int main(int argc, char* argv[])
{
std::string test = ((std::ostringstream&)
(std::ostringstream("") << "This is a test: " << 50.1 << "abc")
).str();
std::cout << test << std::endl;
return 0;
}
This compiles fine in GCC, however the output is the following:
"0x401d0a50.1abc"
So it seems that stringstream treats the first string as a pointer and outputs the address. Subsequent operator<<'s work fine.
How do I fix this?
Thanks!
The reason is that the << operator is a member for void const*, but a free function taking an std::ostream& as the left hand argument for char const*. Your std::ostringstream( "" ) is a temporary: you can call member functions (even non-const member functions) on it, but a temporary cannot be used to initialize the non-const reference of the global function.
EDIT:
Two points: first, as has been pointed out, g++ does do what you
want if you specify -std=c++11. As T.C. points out, this is
specified in §27.7.3.9, which provides a template overload for
all << with an rvalue reference for the std::istream
parameter.
And second, the classic work around is
to start the expression std::ostringstream( "" ).flush() <<.... flush is a member function (and so can be called on
a temporary) which returns an std::ostream& (so everything
else chains nicely); it also does nothing on
a std::ostringstream.
Found it. The C++11 standard special-cases rvalue streams with an extra template operator<< overload. §27.7.3.9 of the standard:
Rvalue stream insertion [ostream.rvalue]
template <class charT, class traits, class T>
basic_ostream<charT, traits>&
operator<<(basic_ostream<charT, traits>&& os, const T& x);
Effects: os << x
Returns: os
It's obviously a better match than the member operator<< that takes a const void * and hence is selected by overload resolution in C++11 mode. In C++98 mode this overload doesn't exist (since there are no rvalue references) and the only viable overload is the member operator<< (since, as James Kanze explains in his answer, the temporary can't bind to the non-const lvalue reference in the free operator<< overload that takes a const char *).

Why does operator>> (or <<) overloading function need to receive an i\ostream reference?

From cplusplus.com, I saw that ostream class's member function operator<< looks like this:
ostream& operator<< (bool val); ostream& operator<< (int val);
.... and so on.
It does make sense because when you use the Cout object like cout<<x you activate the ostream& operator<< (int val) function, so you actually use the << operator on Cout object. This is very much like every other operator and sends the int variable to the function. What is the difference and what exactly happens when I want to stream an object of my own? Why does the syntax is suddenly ostream& operator<< (**ostream &os**, object ob)?
Why do I need to add the ostream var? I am still using cout<<ob so whay isnt it just ostream& operator<< (object obj)? All I pass is my object. The cout object is allready there.
operator<< is generally defined as a free function; that is, not a member function. Since it is an overloaded binary operator, that means it get's its left argument first and its right argument second.
The operator<< traditionally returns a reference to its left argument to enable the idiomatic chain of output.
To make it obvious to the reader, I tend to define my operator overloads using the lhs and rhs abbreviations; an operator<< would look similar to this, for some type T.
std::ostream& operator<<(std::ostream& lhs, T const& rhs)
{
// TODO: Do something
return lhs;
}
As a member function
As with other binary it could be defined as a member function. That is, let us suppose that you with defining your own iostream. Amongst other things, your class declaration may look like this. Again, T is a particular type.
class MyIOStream : public iostream
{
public:
MyIOStream& operator<<(T const& rhs);
}
In this case operator<< is a member function. It has the same semantics when used as <<.
References
Operators in C and C++ - a great summary of all the operators you can overload and their typical arguments.
why do I need to add the ostream var?
I'm sure it's there so that you can chain outputs together:
cout << foo << bar
The first call, cout << foo will result in an ostream reference that can be used for the << bar part.
Some of the stream extractors are members of basic_istream; because they are members, the basic_istream argument is implied. Some of the stream extractors are not members of basic_istream. Because they are not members, the basic_istream argument has to be part of the declaration.
Like this (oversimplified):
class basic_istream {
public:
basic_istream& operator>>(int& i);
}
basic_istream& operator>>(basic_istream&, std::string& str);
Both can be called in the same way:
int i;
std::cin >> i; // calls basic_istream::operator>>(int&)
std::string str;
std::cin >> str; // calls operator>>(basic_istrea&, std::string&)