【发布时间】:2023-03-21 16:20:02
【问题描述】:
我偶然发现了一个我无法理解原因的错误。
我认为它基本上归结为这个错误:
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; 时会发生什么。我相信这是const char* 旁边最常见的调用之一(例如std::out << std::string("Hello world!"))。
错误源于以下几行:
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。
PS。我检查了解决方法,它可以工作。为什么它没有隐式完成?
【问题讨论】:
-
std::string具有转换为const char*的.c_str()成员函数。不行吗? -
en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt 也许您可以使用
(*_sink) << some_arg之类的东西来获取会员和非会员版本。