I'm writing a generic class for logging which
The code:
template<class Writer>
class Logger
{
public:
Logger(Writer* writer);
~Logger(void);
void operator() (char level, std::string message);
private:
Writer* writer;
};
template<class Writer>
Logger<Writer>::Logger(Writer* writer)
: writer(writer)
{
}
template<class Writer>
Logger<Writer>::~Logger(void)
{
}
template<class Writer>
void Logger<Writer>::operator ()(char level, std::string message) {
/* do something fancy with the message */
/* ... */
/* then write to output channel */
this->writer << message;
}
However I get the error "Could not deduce template argument" on compilation. The line the error occurs is
this->writer << message;
I'm pretty new to C++ templates, I'm rather coming from the C#-side of the force... Any suggestions?
Thank you in advance...
You are using a pointer as the left operand of operator <<
:
this->writer << message;
// ^^^^^^
If you want to use a pointer, you should then do:
*(this->writer) << message;
Or even better (provided that a Logger
class must always be associated to a Writer
, so that the writer
pointer should never be null), replace the pointer with a reference:
template<class Writer>
class Logger
{
public:
Logger(Writer& writer);
// ^^^^^^^
// ...
private:
Writer& writer;
// ^^^^^^^
};
This will allow you to use your original version of the call operator, and write:
this->writer << message;
Now all of this of course is correct under the assumption that an appropriate overload of operator <<
exists.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.