Custom manipulator for C++ iostream

前端 未结 4 1540
Happy的楠姐
Happy的楠姐 2020-11-29 02:44

I\'d like to implement a custom manipulator for ostream to do some manipulation on the next item being inserted into the stream. For example, let\'s say I have a custom mani

4条回答
  •  长情又很酷
    2020-11-29 03:05

    [EDIT: "True manipulator semantics" (i.e. a persistent quoting state) could also be achieved by wrapping an std::ostream rather than deriving from it, as noted by Benôit in the comments.]

    To the best of my knowledge this cannot be done directly without either deriving a new class from std::ostream or similar, or wrapping such a class in another class that forwards most methods to its contained std::ostream object. That's because, for the code example you provide to work, you will need to somehow modify the behaviour of std::ostream& operator<<(std::ostream&, std::string const&), which is defined somewhere in the iostreams hierarchy (or possibly wherever std::string is defined). You will also need to use the (somewhat ugly) facilities in ios_base to record a boolean flag holding the current quoting state. Look up ios_base::xalloc(), ios_base::iword() and ios_base::pword() to find out how to do that.

    However, if you are willing to use the following syntax:

    os << "SELECT * FROM customers WHERE name = " << quote(name);
    

    This can be done very simply using a global function (in an appropriate namespace of course).

    This syntax has the advantage that quoting is not persistent, meaning it can't "leak out" when a function sets the quote formatting flag and forgets to set it back to its original value.

提交回复
热议问题