上記の回答の多くとは異なり、テンプレートの魔法を使用して、やりたいことを行うのは非常に簡単です。
ostream(coutはostream)を使用すると、難解な黒魔術(冗談ではない)が必要になる可能性があるため、stringstreamを使用することをお勧めします。
#include <string>
#include <iostream>
#include <sstream>
struct console {
std::stringstream data_;
console() : data_() { };
// We make ourselves a template sink so we can "take" operator<<'s.
// The awesome advantage to using a template like this is that the
// compiler will allow us to "take" any data that can be converted
// to a stringstream, which will handle converting int's etc.
// for us!
template<typename T>
console& operator<<(const T& what) {
data_ << what;
return *this; // We must return a reference if we want to
// string together more than one thing, i.e.
// b << " " << 4;
}
void flush() {
std::cout << data_.str();
data_.clear();
std::cout.flush();
}
};
int main()
{
int a = 4;
console b;
console c;
b.data_ << 2;
c.data_ << 4;
//b << std::cout; // WHAT? it's possible but stupid, prints garbage
// Because we made the template return a reference, this will
// allow us to chain things just like we do with cout.
b << " HELLO WORLD! " << "yo!" << 4;
b << a << " " << 4.2f;
// Compiler chokes on this. It will try to convert "console"
// to a stringstream which it can't.
//b << c;
b.flush(); // Send out the output
// Wait for key press
char foo[500];
gets(foo);
}
出力:
2 HELLO WORLD! yo!44 4.2
もちろん、より多くの制御を行うことを除いて、coutと同じです。バイナリI/Oが必要な場合は、basic_ostreamとbasic_istreamsの使用を開始できますが、本当に必要な場合を除いて、使用しないことをお勧めします。