繁体   English   中英

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

[英]C++ could not deduce template argument

我正在编写一个用于记录的通用类

  1. 可以作为带有要记录的字符串的仿函数调用
  2. 用一些信息(系统时间,日志级别......)丰富字符串
  3. 将日志消息传递给实现<<运算符的输出类。 可以在构造时定义该“输出通道”。

编码:

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;
}

但是我在编译时收到错误“无法推断模板参数”。 发生错误的行是

this->writer << message;

我对C ++模板很陌生,我宁愿来自C#-force of force ...有什么建议吗?

先感谢您...

您正在使用指针作为operator <<的左操作数:

this->writer << message;
//    ^^^^^^

如果你想使用指针,你应该这样做:

*(this->writer) << message; 

甚至更好(假设Logger类必须始终与Writer关联,以便writer指针永远不应为null),请用引用替换指针:

template<class Writer>
class Logger
{
public:
    Logger(Writer& writer);
//         ^^^^^^^
    // ...
private:
    Writer& writer;
//  ^^^^^^^
};

这将允许您使用原始版本的调用操作符,并写入:

this->writer << message;

现在所有这一切当然都是正确的,假设存在operator <<的适当重载。

暂无
暂无

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

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