【发布时间】:2012-04-30 15:59:49
【问题描述】:
我不知道为什么会出错,但我只是想在 endl 中添加一些“类似”的东西,以便我可以将 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;
}
我得到的错误是: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 等,并正确设置了命名空间。我没有收到其他错误。我什至尝试用ostringstream 替换所有出现的basic_ostream 并且没有区别(我稍后会有w_char 版本,但我希望这个简单的案例首先工作)。我在上面一行做了对象,然后在行上传递了一个完全构造好的对象,报错是完全一样的。我已将第二个参数的签名更改为const 和const,也没有任何更改。
关于我在这里做错了什么有什么想法吗?
编辑:因为每个响应似乎都想把它放在那里,我不能使用 std::ostream 因为我希望它只适用于std::ostringstream(和std::basic_ostringstream)而不适用于任何类型的输出流。此外,该函数无论如何都不会用 ostream 编译,因为我使用的是 os.str() 方法,它不在 ostream 中,只有子类。
【问题讨论】:
-
我从未见过有人专门为
std::basic_ostringstream<char>&超载。通常人们只是为std::ostream&超载。 -
您正在为 std::basic_ostringstream 定义一个模板函数,而您的变量是 std::ostringstream。也许这导致您的模板功能无法使用?
-
正如我在原帖中所说:
I even tried replacing all occurrances of basic_ostream with just ostringstream and there was no difference.. 我不能只使用ostream,因为我只希望这个重载适用于ostringstream,而不是所有ostream类型
标签: c++ stringstream