C ++ iostream的自定义操纵器 [英] Custom manipulator for C++ iostream

查看:118
本文介绍了C ++ iostream的自定义操纵器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个自定义的ostream操纵器,对插入到流中的下一个项目做一些操作。例如,假设我有一个自定义操纵符

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 manipulator quote:

std::ostringstream os;
std::string name("Joe");
os << "SELECT * FROM customers WHERE name = " << quote << name;

操纵者 会引用 产生:

SELECT * FROM customers WHERE name = 'Joe'

如何完成?
感谢。

How do I go about accomplishing that? Thanks.

推荐答案

将操纵器添加到C ++流是非常困难的,使用操纵器。可以将新的语言环境嵌入到流中,该流具有安装的面,控制如何打印数字,但不知道如何输出字符串。

It's particularly difficult to add a manipulator to a C++ stream, as one has no control of how the manipulator is used. One can imbue a new locale into a stream, which has a facet installed that controls how numbers are printed - but not how strings are output. And then the problem would still be how to store the quoting state safely into the stream.

字符串是使用 std

Strings are output using an operator defined in the std namespace. If you want to change the way those are printed, yet keeping the look of manipulators, you can create a proxy class:

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 ,而不是简单 string 。它在一些情况下具有与标准操纵器不同的行为。因为它通过返回代理对象工作,所以它不适用于

Which would be suitable to be used for ostream. If you want to generalize, you can make it a template too and also accept basic_stream instead of plain string. It has different behaviors to standard manipulators in some cases. Because it works by returning the proxy object, it will not work for cases like

std::cout << quoting::quote; 
std::cout << "hello";

这篇关于C ++ iostream的自定义操纵器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆