为特定类创建 ostream 操纵器
我有一个从 ostream 派生的类:
class my_ostream: public std::ostream
{
// ...
}
我想制作一个专门针对此类的操纵器(例如 do_something
),如下所示:
my_ostream s;
s << "some text" << do_something << "some more text";
我做了以下操作:
std::ostream &do_something(std::ostream &os)
{
my_ostream *s = dynamic_cast<my_ostream*>(&os);
if (s != NULL)
{
// do something
}
return os;
}
这有效,但更确切地说丑陋的。我尝试了以下方法:
my_ostream &do_something(my_ostream &s)
{
// do something
return s;
}
这不起作用。我还尝试了另一种方法:
class my_ostream: public std::ostream
{
// ...
my_ostream &operator<<(const do_something & x)
{
// do something
return *this;
}
}
这仍然不起作用。
I have a class that is derived from ostream:
class my_ostream: public std::ostream
{
// ...
}
I want to make a manipulator (for example do_something
), that works specifically to this class, like this:
my_ostream s;
s << "some text" << do_something << "some more text";
I did the following:
std::ostream &do_something(std::ostream &os)
{
my_ostream *s = dynamic_cast<my_ostream*>(&os);
if (s != NULL)
{
// do something
}
return os;
}
This works, but is rather ugly. I tried the following:
my_ostream &do_something(my_ostream &s)
{
// do something
return s;
}
This doesn't work. I also tried another approach:
class my_ostream: public std::ostream
{
// ...
my_ostream &operator<<(const do_something & x)
{
// do something
return *this;
}
}
This still doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在类中添加对操纵器的支持:
You need to add support for manipulators in your class: