any system defined user type past to ostream object is converted to a string or char* ?
like cout<<4<<"Hello World";
works perfectly fine, how is this achieved? is the << operator overloaded for each and every type? is there a way to achieve it through just one generic overloaded function? what i mean is can i have just one overloaded operator method with one parameter(like void*) and then decide inside that method how to typecast integer to char*
Things worked partially if i overload operator << using Template i.e
class UIStream
{
private:
ofstream stream;
public:
UIStream();
~UIStream();
template <typename T>
UIStream& operator << (const T);
};
so this works
UIStream my_stream;
my_stream<<"bcd"<10;
however it gives compiler error when i do this
my_stream <<endl;
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'UIStream' (or there is no acceptable conversion)
Is not std::endl a type of object too?
There is just one overloaded function. It doesn't take a
void *
, because that would be useless. If it takes one data type, it isn't overloaded, and it only sees the input value after it's been converted to the type. That means you have no control over how to convert, say, anint
.If you want different behavior between, say, an
int
and achar *
, you need to let the function know somehow what type it is getting, and you need to pass the value in. This is exactly what an overloaded or template function does.yes
this question doesn't make sense .. do you want just one function, or do you want an overloaded function?
After re-reading your question (as a result of a comment in this answer) I have realized that what you want is not only conversions into string (my assumptions in the other answer here), but rather forwarding into the internal ofstream.
Now, what you want to achieve is not simple, and may be overkill in most cases. In the implementation of
[make_string][3]
that I have (that forwards to an internalostringstream
), I don't allow for manipulators to be passed. If the user wants to add a new line (we develop under linux) they just pass a '\n' character.Your problem is forwarding manipulators (
std::hex
,std::endl
...). Your operator<< is defined as taking a constant instance of a type T, but manipulators are function pointers and the compiler is not able to match it against your methods.Manipulators are functions that operate on the
std::basic_ostream
template. Thebasic_ostream
template andostream
class are defined as:Then the possible manipulators that can be passed to a std::ostream are:
If you want to accept manipulators you must provide that overload in your class:
In particular, the signature for endl (which may be the only one you require) is:
so it falls under the
manip1
type of functions. Others, likestd::hex
fall under different categories (manip3
in this particular case)No, you can't. A void * carries no type information, so there is no way of working out what type it actually points to.