Hi All,
I'm trying to build a logging utility. It creates an object that can be used just like a std::cout. The added benefit of this object is that it can simultaneously output to a log file, console, add headers to the start of lines, etc based on a mask that is set.
The part that is not working right now is the fact that it cannot accept std::endl. My code is below (
R0mai helped):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class logger {
public:
logger( const char* filename); // Opens a file for use with ofstream fout.
~logger(); // Flushes and closes the logging file.
logger& operator()(unsigned mask_); // Allows us to set the mask in the same line as the messages
template<class LogInputTemplate>
friend logger& operator<<( logger& log, const LogInputTemplate& output );
private:
std::ofstream fout;
unsigned mask;
};
template<class LogInputTemplate>
logger& operator<<( logger& log, const LogInputTemplate& output ) {
if (log.mask & 0xf0) std::cout << output;
if (log.mask & 0x0f) log.fout << output;
return log;
}
|
Now, if I use the following in my code, I want it to compile:
1 2
|
logger MyLog("MyLog.txt");
MyLog(0xff)<<"Hello World"<< std::endl;
|
It works fine unless I use the std::endl. Then I get the following compilation error:
error C2914: 'operator <<' : cannot deduce template argument as function argument is ambiguous
error C2676: binary '<<' : 'logger' does not define this operator or a conversion to a type acceptable to the predefined operator |
Now, I've looked up std::endl and in ostream.h it appears to be defined by a series of templates, classes, inlines and defines that don't mean a lot to me other than it places a \n and then flushes. So really, I'm dealing with something that doesn't fit into a template class.
I checked out this site which seems to suggest that std::endl is an ostream& object.
http://cplusplus.com/reference/iostream/manipulators/endl/
Therefore I figure I can add one more overloading function to carry out the duties of endl:
1 2 3 4 5 6
|
logger& operator<<( logger& log, std::ostream& os)
{
if (log.mask & 0xf0) std::cout << std::endl;
if (log.mask & 0x0f) log.fout << std::endl;
return log;
}
|
However now I get the following error:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
logger.h(13): could be 'logger &operator <<(logger &,std::ostream &) while trying to match the argument list '(logger, overloaded-function) |
I consider this a partial success because it at least recognizes the function that I've been trying to direct the endl to. Does anyone know what I can do from here?