c++ - 如何为允许表达语法的 cout 编写函数包装器?

标签 c++ wrapper cout

我想包装 std::cout 以进行格式化,如下所示:

mycout([what type?] x, [optional args]) {
    ... // do some formatting on x first
    std::cout << x;
}

并且仍然能够使用像

这样的富有表现力的语法
mycout("test" << i << endl << somevar, indent)

而不是被迫像这样更冗长

mycout(std::stringstream("test") << i ...)

我该如何实现?制作什么类型的 x

编辑:增加了对可选参数的考虑

最佳答案

这个怎么样:

struct MyCout {};

extern MyCout myCout;

template <typename T>
MyCout& operator<< (MyCout &s, const T &x) {
  //format x as you please
  std::cout << x;
  return s;
}

然后放MyCout myCout;进入任何一个 .cpp 文件。

然后您可以使用 myCout像这样:

myCout << "test" << x << std::endl;

它会调用模板 operator<<可以进行格式化。

当然,如果需要,您也可以为特定类型的特殊格式提供运算符重载。

编辑

显然(感谢@soon),要使标准操纵器正常工作,还需要一些重载:

MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ostream &)) {
  f(std::cout);
  return s;
}

MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios &)) {
  f(std::cout);
  return s;
}

MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios_base &)) {
  f(std::cout);
  return s;
}

编辑 2

我可能稍微误解了您最初的要求。这个怎么样(加上与上面相同的操纵器重载):

struct MyCout
{
  std::stringstream s;

  template <typename T>
  MyCout& operator << (const T &x) {
    s << x;
    return *this;
  }

  ~MyCout() {
    somehow_format(s);
    std::cout << s.str();
  }
};

int main() {
  double y = 1.5;
  MyCout() << "test" << y;
}

关于c++ - 如何为允许表达语法的 cout 编写函数包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444119/

相关文章:

c++ - 我如何访问静态类成员?

c++ - 智能指针数组删除器

c# - C# 托管代码和 C++ 非托管代码之间字符串的混合编程

c++ - 一个应用程序中的 MPI_Scatter 和 MPI_Bcast 解决方案。如何让分区打印分区大小

c++ - 将字符串解析为数字或数字和百分号

java - 扩大和装箱 Java 原语

java - 弗林克 : Wrap executable non-flink jar to run it in a flink cluster

c++ - 在 cout 中打印 getline() 字符串时出现奇怪的错误

c++ - std::cout 不喜欢条件 if 中的 std::endl 和字符串

c++ - 错误: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'List' )