我想包装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;
}

09-06 20:25