简短回答:继续使用强制转换或toStr()
,或编写自己的operator<<
函数。(我更愿意l1.toStr()
。(string)l1
)
长答案:如果标准库有一个函数,这可能会起作用
std::ostream& operator<<( std::ostream&, std::string const& );
它几乎可以做到,但在技术上不是。两者ostream
和string
都是模板实例化的类型定义。还有一个模板函数可以将一个插入另一个。
// This is somewhat simplified. For the real definitions, see the Standard
// and/or your complying implementation's headers.
namespace std {
typedef basic_string<char> string;
typedef basic_ostream<char> ostream;
template <typename CharT>
basic_ostream<CharT>& operator<<(
basic_ostream<CharT>&,
basic_string<CharT> const&);
}
因此,当您使用cout << str
where 的类型时str
,std::string
它可以计算出使用该模板函数,与CharT = char
.
但是 C++ 不允许您让编译器在同一个调用中找出隐式类型转换 ( Literal
to string
) 和推断模板函数模板参数 ( CharT = char
)。