我偶然发现了一个我无法理解原因的错误。
我认为这基本上归结为这个错误:
error: no matching function for call to ‘std::basic_ostream<char>::operator<<(const std::basic_string<char>&)’
我查看了关于 www.cplusplus.com 的规范事实上它说没有定义 std::ostream::operator<<
与 std::string
作为论点。
我的问题是,写 std_ostream_instance << std_fancy_string;
会发生什么? .我相信这是最常见的调用之一(例如 std::out << std::string("Hello world!")
),仅次于 const char*
。 .
错误源于这些行:
template<typename T>
void Log::_log(const T& msg)
{ _sink->operator<<( msg ); }
_sink
被定义为 std::ostream*
周围有一些包装函数,但它在这里中断。
我想我可以通过写来解决
template<>
void Log::_log<std::string>(const std::string& msg) {
_sink->operator<<( msg.c_str() );
}
因为有 ostream& operator<< (ostream& out, const unsigned char* s );
默认定义。
我只是看不出为什么没有自动猜到它,因为它显然可以像 cout << any_std_string
这样简单地使用。 .
不确定这是否相关,但我希望能够通过我的日志函数传递任何 std::ostream
无法处理的内容.我使用了明确的非模板声明,但决定为 log(const T& anything_to_log)
移动到模板重构它。有 5 个以上的重载似乎很愚蠢。当我尝试编译类似 Log::log( std::string("test case") )
的内容时出现错误.
它看起来很简单,但我自己搞不定。尝试谷歌和搜索堆栈无济于事。
问候,luk32。
附言。我检查了解决方法,它有效。为什么不隐式完成?
最佳答案
operator <<
重载不是 ostream
的成员.它们是独立的功能,例如
ostream& operator << ( ostream& out, const basic_string<T>& bs );
尝试
template<typename T>
void Log::_log(const T& msg)
{ *_sink << msg; }
关于c++ - std::ostream::operator<< 没有为 std::string 定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12424897/