I'm trying to write a stream manipulator with arguments.
I have class with 3 int's CDate(Year, Month, Day).
So I need to make manipulator date_format(const char*)
.
e.g. :
CDate a(2006, 5, 15);
cout <<"DATE IS : " << date_format("%Y-hello-%d-world-%m-something-%d%d") << a;
Output will be :
DATE IS : 2006-hello-15-world-5-something-1515
Guess i need to use that
ios_base & dummy_date_format_manipulator ( ios_base & x )
{
return x;
}
ios_base & ( * ( date_format ( const char * fmt ) ) )( ios_base & x )
{
return dummy_date_format_manipulator;
}
but i don't know how.
You can use pword
array for this.
Every iostream in C++ has two arrays associated with it.
ios_base::iword - array of ints
ios_base::pword - array of void* pointers
You can store you own data in it. To obtain an index, that refers to an empty element in all iword
and pword
arrays you should use function std::ios_base::xalloc()
. It returns int that you can use as an unique index in *word
.
You should obtain that index once on the start-up, and than use it for all operations with *word
.
Then programming your own manip will look like:
Manipulator function, that receives reference to ios_base
object and pointer to the format string, simply stores that pointer in pword
iosObject.pword(index_from_xalloc) = formatString
Then overloaded operator <<
(>>
) obtains format string from the iostream object in the same way. After that you just make a conversion referencing to the format.