c++ - 为同一对象管理多个流运算符(operator<<, >>)

标签 c++ namespaces operator-overloading

我希望能够为对象定义流运算符( <<>> ),但要有多个流运算符,以便我可以根据上下文使用不同的集合。例如,如果我有一个对象如下:

struct Foo {
  int a;
};

然后在某些地方我希望能够使用这个

std::ostream& operator<<(std::ostream& out, const Foo& foo) {
  out<<foo.a;
}

在其他情况下我更愿意使用这个

std::ostream& operator<<(std::ostream& out, const Foo& foo) {
  out<<"'"<<foo.a<<"'";
}

但我看不出如何同时定义这两者。

我正在提交我自己的答案,但我希望其他人在过去有理由比我更深入地思考这个问题,并且最好在大型应用程序中有一个有组织的方式来做这件事(因此术语“问题标题中的“管理”)。

最佳答案

创建一个操纵器:一个简单的代理,它只为替代格式提供一个名称(和一个重载槽)。

// default format
std::ostream& operator<<(std::ostream& out, const Foo& foo) {
  return out<<foo.a;
}

// custom format

// helper class
struct print_quoted_manip {
    Foo const &ref;

    print_quoted_manip( Foo const &in )
        : ref( in ) {}
};

// implementation
std::ostream& operator<<( std::ostream& out, print_quoted_manip o )
    { return out << '\'' << o.ref << '\''; }

// the manipulator
print_quoted_manip print_quoted( Foo const &in )
    { return print_quoted_manip( in ); }

// usage
std::cout << print_quoted( my_foo );

您可以轻松地将其模板化以在任何类型的对象周围加上引号。

关于c++ - 为同一对象管理多个流运算符(operator<<, >>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16335060/

相关文章:

C++字符串拆分但转义引号中的所有定界符

c++ - 为什么 Clang 会添加额外的 FMA 指令?

c++ - 复制构造函数和动态分配

c++ - 将函数限制在命名空间

c# - XML 反序列化仅适用于 xml 中的命名空间

c++ - 如果我不正确地重载运算符会报告什么错误?

c++ - 运算符重载 operator= 使用友元函数

c++ - 什么是合约(为 C++17 提议的)?

c++ - 代理语法错误 : What am I doing wrong?

PHP:如何在主命名空间中导入子命名空间?