Create ostream manipulators for a specific class
I have a class derived from ostream:
class my_ostream: public std::ostream
{
// ...
}
I want to make a manipulator (for example do_something
) that works specifically for this class, for example:
my_ostream s;
s << "some text" << do_something << "some more text";
I did the following:
std::ostream &do_something(std::ostream &os)
{
my_ostream *s = dynamic_cast<my_ostream*>(&os);
if (s != NULL)
{
// do something
}
return os;
}
It works, but it's pretty ugly. I tried the following:
my_ostream &do_something(my_ostream &s)
{
// do something
return s;
}
This does not work. I also tried a different approach:
class my_ostream: public std::ostream
{
// ...
my_ostream &operator<<(const do_something & x)
{
// do something
return *this;
}
}
It still doesn't work.
+2
a source to share
1 answer
You need to add support for manipulators in your class:
#include<iostream>
class my_ostream : public std::ostream
{
public:
std::string prefix;
my_ostream():prefix("*"){}
// manipulator support here:
my_ostream& operator<<( my_ostream&(*f)(my_ostream&)){
f(*this);
return *this;
}
};
my_ostream& operator<<(my_ostream &st, const std::string &s){
std::cout << st.prefix << s;
return st;
}
// manipulator: clear prefix
my_ostream& noprefix(my_ostream &st){
st.prefix="";
}
int main(){
my_ostream s;
std::string str1("text");
std::string str2("text");
s << str1 << noprefix << str2;
}
+3
a source to share