[英]Cannot std::cout an implicitly converted std::string
我曾经通过std::cout << str << std::endl
显示字符串,并认为 object 隐式转换为std::string
也可以以这种方式显示。
然而,我注意到我错了。 在我为 std::string 重载operator <<
之前,我无法std::cout
隐式转换的std::string
::string。
以下代码演示了上述内容。
#include <stdio.h>
#include <iostream>
#include <string>
class X
{
public:
operator std::string() const {
return std::string("world");
}
};
#ifdef OVERLOAD_STREAM_OP
std::ostream& operator<<(std::ostream& os, const std::string& s) {
return os << s;
}
#endif
int main() {
std::string s = "hello";
std::cout << s << std::endl; // viable
printf("---\n");
X x;
std::cout << x << std::endl; // not viable
return 0;
}
看来,在 STL 实现中,std::string 类型的重载operator <<
function 有点不同(但我真的不明白那些模板的东西):
template<typename _CharT, typename _Traits, typename _Allocator>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const basic_string<_CharT, _Traits, _Allocator>& __str)
{ return __os << __str._M_base(); }
我的问题:
STL 的重载operator <<
和我自己的std::string
类型的重载operator<<
符 << 有什么区别?
为什么我不能用std::cout
显示隐式转换的 std::string object x
(编译错误)?
- STL 的重载
operator <<
和我自己的 std::string 类型的重载operator<<
符 << 有什么区别?
您的operator<<
是非模板,而 STL 的一个是模板。
- 为什么我不能用
std::cout
显示隐式转换的std::string
object x (编译错误)?
模板参数推导中不会考虑隐式转换(从X
到std::string
),这会导致对模板operator<<
的调用失败。 另一方面,非模板operator<<
没有这样的问题。
类型推导不考虑隐式转换(除了上面列出的类型调整):这是重载解析的工作,稍后会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.