简体   繁体   English

C ++无法推断出模板参数

[英]C++ could not deduce template argument

I'm writing a generic class for logging which 我正在编写一个用于记录的通用类

  1. can be called as a functor with the string to log 可以作为带有要记录的字符串的仿函数调用
  2. enriches the string with some information (system time, log level, ...) 用一些信息(系统时间,日志级别......)丰富字符串
  3. passes the log message to an output class which implements the << operator. 将日志消息传递给实现<<运算符的输出类。 This "output channel" can be defined upon construction. 可以在构造时定义该“输出通道”。

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? 我对C ++模板很陌生,我宁愿来自C#-force of force ...有什么建议吗?

Thank you in advance... 先感谢您...

You are using a pointer as the left operand of operator << : 您正在使用指针作为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: 甚至更好(假设Logger类必须始终与Writer关联,以便writer指针永远不应为null),请用引用替换指针:

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. 现在所有这一切当然都是正确的,假设存在operator <<的适当重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM