我不知道为什么这是错误的,但我只是想在endl中添加"akin",以便我可以将ostringstream中的内容添加到调试器中.我有以下内容:
class debug_stream_info
{
public:
debug_stream_info(int errorLine, char *errorFile, int level)
:m_errorLine(errorLine), m_errorFile(errorFile), m_logLevel(level)
{
}
friend std::basic_ostringstream<char>& operator<<(std::basic_ostringstream<char>& os, debug_stream_info& debug_info);
private:
int m_errorLine;
std::string m_errorFile;
int m_logLevel;
};
std::basic_ostringstream<char>& operator<<(std::basic_ostringstream<char>& os, debug_stream_info& debug_info)
{
// Write the stream's contents to cpu_debug
// Deleted custom logging function. No errors here though
// Clear the stream for re-use.
os.str("");
os.seekp(0);
return os;
}
int main(int argc, char** argv)
{
std::ostringstream myout;
myout << "hey there" << " and some more " << "Numbers!!: " << 435 << 54.2 << " that's good for numbers" << debug_stream_info(__LINE__, __FILE__, LOG_LEVEL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'debug_stream_info' (or there is no acceptable conversion)对于main中的行.这是在VS2008上.
我包括sstream,iostream等,并且命名空间设置正确.我没有其他错误.我甚至尝试用basic_ostream公正替换所有出现的事情ostringstream并没有区别(我稍后会有一个w_char版本,但我希望简单的情况首先工作).我在上面的行上创建了对象,然后在行上传递了一个完全构造的对象,错误完全相同.我已经改变了第二个参数的签名,也const没有改变.
关于我在这里做错了什么的想法?
编辑:因为每个响应似乎都想把它放在那里,我不能使用std :: ostream因为我希望这只适用于std::ostringstream(和std::basic_ostringstream)而不适用于任何类型的输出流.此外,该函数无论如何都不会使用ostream进行编译,因为我正在使用os.str()不在ostream中的方法,只使用子类.
您的代码的真正问题在于您已经过载std::ostringstream而不是std::ostream.所以如果你写这个代码你的代码会工作:
debug_stream_info info(/** blah blah**/);
std::ostringstream oss;
oss << info ; //OK
Run Code Online (Sandbox Code Playgroud)
但是这不起作用:
oss << 1 << info; //ERROR
Run Code Online (Sandbox Code Playgroud)
这是编译错误,因为表达式oss<<1返回一个类型的对象,该对象std::ostream&没有debug_stream_info作为第二个参数的重载.这意味着如果你使用cast作为:
static_cast<std::ostringstream&>(oss << 1) << info; //OK
Run Code Online (Sandbox Code Playgroud)
那应该再次起作用.
所以解决方案是超载std::ostream,而不是std::basic_ostringstream.
另外,第二个参数应该是const &.这也是您的代码的问题.
写这个:
std::ostream& operator<<(std::ostream&, debug_stream_info const &);
//^^^^^^^ note this
Run Code Online (Sandbox Code Playgroud)
第二个参数应该是const &您可以将临时对象写入流.