C ++ fstream-创建自己的格式标志 [英] c++ fstream - creating own formatting flags

查看:96
本文介绍了C ++ fstream-创建自己的格式标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为输出文件的格式创建新的标志.我上课

i need to create new flags for the format of the output file. i have a class

class foo{
    bar* members;
    ofstream& operator<<(ofstream&);
    ifstream& operator>>(ifstream&);
};

我想像这样使用它:

fstream os('filename.xml');
foo f;
os << xml << f;
os.close();

这将保存一个 xml 文件.

fstream os('filename.json');
foo f;
os << json << f;
os.close();

和一个 json 文件.

我该怎么做?

推荐答案

您可以轻松创建自己的操纵器,也可以劫持现有操纵器 标志或使用std::ios_base::xalloc获得新的特定流 记忆,例如(在Foo的实现文件中:

You can easily create yor own manipulators, either hijacking an existing flag or using std::ios_base::xalloc to obtain new stream specific memory, e.g. (in the implementation file of Foo:

static int const manipFlagId = std::ios_base::xalloc();

enum
{
    fmt_xml,        //  Becomes the default.
    fmt_json
};

std::ostream&
xml( std::ostream& stream )
{
    stream.iword( manipFlagId ) = fmt_xml;
    return stream;
}

std::ostream&
json( std::ostream& stream )
{
    stream.iword( manipFlagId ) = fmt_json;
    return stream;
}

std::ostream&
operator<<( std::ostream& dest, Foo const& obj )
{
    switch ( dest.iword( manipFlagId ) ) {
    case fmt_xml:
        // ...
        break;
    case fmt_json:
        //  ...
        break;
    default:
        assert(0);  //  Or log error, or abort, or...
    }
    return dest;
}

在标头中声明xmljson,作业完成.

Declare xml and json in your header, and the job is done.

(话虽如此,我认为这有点滥用 机械手.诸如xml之类的格式不仅限于简单的本地格式,而且 最好由拥有ostream的单独类处理,并且 写入整个流,而不仅仅是单个对象.)

(Having said this, I rather think that this is a bit of an abuse of manipulators. Formats like xml go beyond simple, local formatting, and are best handled by a separate class, which owns the ostream, and writes the entire stream, and not just individual objects.)

这篇关于C ++ fstream-创建自己的格式标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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