Do you ever get the feeling when you're working with std ostreams that there's just way too much typing going on? I do. Never quite understood why the left-shift operator was chosen either.
So thinking about it for a bit and wondering just how much time and effort it would take to put a better output interface together. Started coding and then something like twelve lines of code later, I'm done!
Code:
/* osprint.hpp */
#include <iostream>
struct osprint
{
std::ostream& stream;
osprint()
: stream(std::cout)
{ }
osprint(std::ostream& stream)
: stream(stream)
{ }
template <typename V>
osprint& operator = (const V& rhs)
{
stream << rhs;
return *this;
}
};
template <typename V>
inline osprint& operator , (osprint& lhs, const V& rhs)
{
return lhs = rhs;
}
#include <string>
const std::string eol = "\n";
/* Usage */
#include <cmath>
using namespace std;
osprint out;
int main()
{
out = "Euler's number is ", exp(double(1)), eol;
}
If that isn't a testament to the power of C++, I don't know what is!
Anyway, I just like the interface better. Plus it's about half as much typing. Kind of doesn't work for those who use commas a lot to separate statements of course. But who really does that anyway?