我想为ostream实现一个自定义操纵器,对插入到流中的下一个项目进行一些操作.例如,假设我有一个自定义操纵器引用: std::ostringstream os;std::string name("Joe");os "SELECT * FROM customers WHERE name
std::ostringstream os; std::string name("Joe"); os << "SELECT * FROM customers WHERE name = " << quote << name;
操纵者引用将引用名称以产生:
SELECT * FROM customers WHERE name = 'Joe'
我该如何完成呢?
谢谢.
使用std命名空间中定义的运算符输出字符串.如果要更改打印方式,同时保持操纵器的外观,可以创建代理类:
namespace quoting { struct quoting_proxy { explicit quoting_proxy(std::ostream & os):os(os){} template<typename Rhs> friend std::ostream & operator<<(quoting_proxy const& q, Rhs const& rhs) { return q.os << rhs; } friend std::ostream & operator<<(quoting_proxy const& q, std::string const& rhs) { return q.os << "'" << rhs << "'"; } friend std::ostream & operator<<(quoting_proxy const& q, char const* rhs) { return q.os << "'" << rhs << "'"; } private: std::ostream & os; }; struct quoting_creator { } quote; quoting_proxy operator<<(std::ostream & os, quoting_creator) { return quoting_proxy(os); } } int main() { std::cout << quoting::quote << "hello" << std::endl; }
哪个适合用于ostream.如果要进行概括,可以将其设为模板,也可以接受basic_stream而不是普通字符串.在某些情况下,它与标准操纵器有不同的行为.因为它通过返回代理对象来工作,所以它不适用于像
std::cout << quoting::quote; std::cout << "hello";