![](/img/trans.png)
[英]Why cannot use cout with user-defined conversion to std::string?
[英]Is possible to get automatic cast from user-defined type to std::string using cout?
在问题中,如果我在我的类中定义一个字符串运算符:
class Literal {
operator string const () {
return toStr ();
};
string toStr () const;
};
然后我用它:
Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;
使用显式转换一切正常,但如果我删除(字符串)编译器说它需要在std :: string中声明的强制转换运算符。 它不应该自动投射我的类型? 解决:我正在重载运算符<<(ostream&os,const Literal&l)。
不.. std :: string必须有一个构造函数,将Literal作为参数。
你可以做的是为你的Literal类重载operator <<并将它转换并插入到那里的流中。
ostream &operator <<(std::ostream &stream, const Literal &rhs)
{
stream << (string) rhs;
return stream;
}
简短回答:继续使用toStr()
或toStr()
,或编写自己的operator<<
function。 (我更喜欢l1.toStr()
到(string)l1
。)
答案很长:如果标准库有一个功能,这可能会有效
std::ostream& operator<<( std::ostream&, std::string const& );
它几乎可以做到,但不是技术上的。 ostream
和string
都是模板实例化的typedef。 并且有一个模板功能可以将一个插入另一个。
// 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
其中的类型str
是std::string
,就可以计算出使用该模板的功能,与CharT = char
。
但是C ++不允许你让编译器同时在同一个调用中找出隐式类型转换( Literal
to string
)和演绎模板函数模板参数( CharT = char
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.