是否可以使用 cout 从用户定义类型自动转换为 std::string ?
正如问题中所示,如果我在类中定义一个字符串运算符:
class Literal {
operator string const () {
return toStr ();
};
string toStr () const;
};
然后使用它:
Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;
通过显式强制转换一切都会正常,但是如果我删除 (string) 编译器会说它需要在 std 中声明的强制转换运算符: :细绳。它不应该自动转换我的类型吗? 已解决:我正在重载运算符<< (ostream&os, const Literal&l)。
As in the question, if I define a string operator in my class:
class Literal {
operator string const () {
return toStr ();
};
string toStr () const;
};
and then I use it:
Literal l1 ("fa-2bd2bc3e0");
cout << (string)l1 << " Declared" << endl;
with an explicit cast everything goes right, but if I remove the (string) the compiler says that it needs a cast operator declared in std::string. Shouldn't it cast my type automatically?
SOLVED: I'm overloading operator<< (ostream& os, const Literal& l).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不.. std::string 必须有一个以 Literal 作为参数的构造函数。
你可以做的是重载运算符 <<对于你的 Literal 类,让它强制转换并插入到那里的流中。
No.. std::string would have to have a constructor that took Literal as an argument.
What you could do is overload operator << for your Literal class and have it cast and insert into the stream in there.
简短回答:继续使用强制转换或 toStr(),或者编写您自己的运算符<< 函数。 (我更喜欢
l1.toStr()
而不是(string)l1
。)长答案:
如果标准库有一个
几乎可以实现的功能,那么这可能会起作用,但从技术上讲却不行。
ostream
和string
都是模板实例化的真正类型定义。还有一个模板函数可以将一个插入另一个。因此,当您使用
cout << str
其中str
的类型是std::string
,它可以找出使用该模板函数,其中CharT = char
>。但 C++ 不允许编译器找出隐式类型转换(
Literal
到string
)并推导模板函数模板参数(CharT = char
)在同一个调用中。Short answer: Keep using a cast or
toStr()
, or write your ownoperator<<
function. (I would preferl1.toStr()
to(string)l1
.)Long answer:
This might work if the Standard Library had a function
Which it almost does, but not technically. Both
ostream
andstring
are really typedefs of template instantiations. And there's a template function for inserting one into the other.So when you use
cout << str
where the type ofstr
isstd::string
, it can figure out to use that template function, withCharT = char
.But C++ doesn't allow you to have the compiler figure out both an implicit type conversion (
Literal
tostring
) and deduce template function template parameters (CharT = char
) on the same call.