-1

如何仅ostream使用从头开始实现 -like 类printf
对我来说,问题在于选择格式字符串,这实际上等于识别输入的类型和处理精度

4

3 回答 3

1

我假设您的意思是“类似类”operator<<的重载。ostream仅通过重载就很容易识别函数参数的类型。例如,您可能有:

ostreamlike& ostreamlike::operator<<(int x)
{
  printf("%d", x);
  return *this;
}

ostreamlike& ostreamlike::operator<<(float x)
{
  printf("%f", x);
  return *this;
}

输出的格式由选择的重载决定。

于 2013-04-05T11:30:56.933 回答
1

想想,可能是这样的

#include <stdio.h>

class ostreamlike {
public:
  ostreamlike(FILE* f_): f(f_) {}

  ostreamlike& write(int n) {
    fprintf(f, "%d", n);
    return *this;
  }

  ostreamlike& write(const char* n) {
    fprintf(f, "%s", n);
    return *this;
  }

private:
  FILE* f;
};

// operator for types that is supported ostreamlike internally
template <typename type>
ostreamlike& operator<<(ostreamlike& stream, const type& data) {
  return stream.write(data);
}

// external implementations to write using ostreamlike
ostreamlike& operator<<(ostreamlike& stream, bool data) {
  return stream.write(data ? "true" : "false");
}

int main() {
  ostreamlike s(stdout);
  s << "hello " << 1 << " : " << true << "\n";
  return 0;
}
于 2013-04-05T11:40:47.883 回答
0

这取决于ostream你想要接近真实的程度。假设你想正确地做到这一点,你还需要一个streambuf派生类。ostream仅进行格式化,实际的 I/O 由内部streambuf派生类完成。由于streambuf没有未格式化的 I/O,您需要使用fwritenot printf

如果您的目标只是在已经存在的FILE*指针上执行 I/O,那么这就是要走的路。你从 say 派生一个类streambufstreambuf_with_FILE然后从ostreamsay派生另一个类ostream_with_FILEstreambuf_with_FILE覆盖适当的方法来执行实际的 I/O 并ostream_with_FILE具有一个内部streambuf_with_FILE对象。实际上只需要很少的代码。

于 2013-04-05T11:34:44.340 回答