This is a exercise for school, so please provide just hints and no complete examples ;-)
I have my own manipulator:
template<typename T, typename Tr=char_traits<T> >
ios_base& toggle(basic_ios<T,Tr>& io)
{
if(io.flags() & ios::scientific)
{ io.unsetf(ios::scientific); io.flags(ios::fixed); }
else { io.unsetf(ios::fixed); io.flags(ios::scientific); }
return io;
}
I wrote this, because I have to write a manipulator with the form ios_base& my_manip(basic_ios&)
.
If I use it like this (without using return value):
toggle(cout);
... that works fine. But if I use it like that:
toggle(cout) << 54444.6456555 << endl;
That does not work (Because std::ios_base does not have operator<<() as stated below).
In general I do not get what ios_base& my_manip(basic_ios&)
could be useful for... Do you have a hint/example?
You guys already helped me a lot! What I still do NOT understand, is the motivation to pass a basic_ios
and give back ios_base
(because that is suggested to do in the exercise I have to solve...). What could be a possible scenario to use this???
operator<<
forstd::ostream
s: en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt – Trexlerios_base
has nooperator>>
noroperator<<
defined. That's whytoggle(cout) << "something"
doesn't work. – Trexlerendl
is defined – Trexlerios_base& my_manip(basic_ios&)
(even though I do not get what it could be useful for...) – Dickiestd::ostream
has severaloperator<<
overloads that take function pointers and calls them. Using manipulators likestd::endl
,std::hex
or your own is typically done by calling theoperator<<
(oroperator>>
foristream
s) of the stream and passing a pointer to the manipulator function. Note that function names decay to pointers to those functions. – Trexlerstd::ostream
is a typedef forstd::basic_ostream<char>
. There's alsostd::wostream
, a typedef forstd::basic_ostream<wchar_t>
. – Trexlerbasic_ios
and give backios_base
" Nobody spotted that yet :D -- It's an error if the manipulator is intended to be used asstream<<toggle
. It has to be eitherbasic_ios<T,Tr>& my_manip(basic_ios<T,Tr>&)
orios_base& my_manip(ios_base&)
. In your case, I think the base classios_base
is sufficient, it already provides the necessary functionality and is therefore the more general choice (see this class diagram). When usingios_base
, you don't need a function template. – Trexler