c++ - std::ostream::operator<< 没有为 std::string 定义?

标签 c++ std stdstring ostream

我偶然发现了一个我无法理解原因的错误。

我认为这基本上归结为这个错误:

 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/

相关文章:

c++ - C++98 互斥体中共享数组的锁定变量

c++ - 将数组分配给更高维的数组

当 base 不在 [2,36] (GCC) 中时,C++11 std::stoi 静默失败

c++ - 我可以在 vector 中使用 `unique_ptr` 吗,还是需要切换到 `shared_ptr` ?

c++ - 通过单次迭代删除所有逗号、点和小写字符串

c++ - 如何让我的类(class)与 std::string operator+ 一起工作

c++ - 是否可以模板化 basic_string<>::iterator?

c++ - 创建一个使用模板创建类或子类对象的函数

c++ - [[可能]] 和 [[不太可能]] 影响程序汇编的简单示例?

c++ - 连接字符串不能按预期工作