Reputation: 5849
I intend to call a function whenever m_logger<<"hello"<<"world"
is called. m_logger is of type ofstream.
So i decide to overload << with following signature
friend ofstream& operator<<(ofstream &stream,char *str);
However the vc compiler gives following error:
error C2666: 'operator <<' : 6 overloads have similar conversions
Is there anyother way to achieve this, my objective is to divert all the write operation to ofstream object to different function?
Creating an object of my own calss works for me, however how can i make it work like normal ofstream object which typecasts all system defined types into strings or char*. i know one approach would be to overload the operator for each and every type but is there a cleaner approach
Upvotes: 0
Views: 1965
Reputation: 27008
The problem is that ofstream
is already overloaded this way. If you make mlogger
of a new type holding an ofstream
, then you can do this:
class mlogger_t {
public:
ofstream stream;
...
}
mlogger_t& operator<<(mlogger_t& stream, const string& str) {
stream.stream << str;
...
}
//EDIT: here is how to make this work for other types too using templates:
template<typename T> mlogger_t& operator<<(mlogger_t& stream, T val) {
stream.stream << val;
}
...
mlogger_t mlogger;
mlogger << "foo";
Also, you should definitely use a const string&
(as I did in this example) rather than a C-style string. If you really need it to be C-style, at least use const char *
.
Upvotes: 2
Reputation: 52334
Depending on why you want to overload operator<<, the correct solution is either
Like this:
template <typename T>
myStream& operator<<(myStream& s, T const& v)
{
s.getStream() << v;
}
and you'll see that manipulators don't match the template, so you'll also need something like:
myStream& operator<<(myStream& fl, std::ostream& (*fn)(std::ostream&))
{
s.getStream() << fn;
}
Upvotes: 2
Reputation: 67847
What you should do is make a class and then define operator<<
. An operator overload must contain at least one user-defined type. Similarly, you can't write a new operator+(int, int)
.
Upvotes: 1
Reputation: 101665
"overload" isn't "override". You can overload a function or operator for arguments of different types; you cannot override an existing function or operator with your own implementation (aside from overriding virtual functions, which is obviously very different). The only exceptions are operator new
and operator delete
, where it's possible to override built-in ones.
Upvotes: 5