[英]ostream operator<< call parent ostream
code: 码:
cout << "11122333" << endl;
expect: 期望:
11122333\\n 11122333 \\ n
result: 结果:
11122333\\n 11122333 \\ n
All right. 好吧。
code: 码:
cout.operator<<("11122333");
cout.operator<<(endl);
expect: 期望:
11122333\\n 11122333 \\ n
result: 结果:
00B273F8\\n 00B273F8 \\ n
(or some other address, it's cast to void*
:( ) (或其他地址,将其转换为
void*
:()
trouble: Want write class derived from ostream
麻烦:想写从
ostream
派生的类
class SomeStream : public ostream
{
public:
explicit SomeStream(streambuf* sb) : ostream(sb) { }
template <typename T> SomeStream &operator <<(const T &val)
{
std::ostream::operator<<(val); //Trouble in there!
std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl;
/*some other behavior*/
return *this;
}
SomeStream &operator <<(ostream& (*val) (ostream&))
{
std::ostream::operator<<(val);
/*some other behavior*/
return *this;
}
SomeStream &operator <<(ios_base& (*val) (ios_base&))
{
std::ostream::operator<<(val);
/*some other behavior*/
return *this;
}
};
When I call parent operator std::ostream::operator<<(val);
当我调用父运算符
std::ostream::operator<<(val);
val cast to void*
and not normal work. val转换为
void*
而不是正常工作。 How it right to do? 正确的做法是什么? and why direct call
operator<<
for ostream
work not same as indirect call. 以及为什么
ostream
直接调用operator<<
与间接调用不同。
The output operator <<
for const char*
is not a member of type ostream
. const char*
的输出operator <<
不是ostream
类型的成员。 Only those overloads are member functions, one of them is for void*
. 只有那些重载才是成员函数,其中之一是
void*
。 There are also non-member overloads . 也有非成员重载 。
There is workaround: 有解决方法:
template <typename T> SomeStream &operator <<(const T &val)
{
static_cast<std::ostream&>(*this) << val; //Trouble in there!
std::cout << "<<" << " " << typeid(T).name() << " " << val << std::endl;
/*some other behavior*/
return *this;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.