Custom manipulator for class

后端 未结 4 1683
轮回少年
轮回少年 2021-01-27 07:21

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*)

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 07:37

    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.

提交回复
热议问题