1

I have been using Petru's logging framework a bit. This is part of his code:

class Output2FILE
{
public:
  static FILE*& Stream() {
    static FILE* pStream = stderr;
    return pStream;
  }
};

Which is very nice as it simply logs to stderr without any action, but with the function that can afterwards be set to anything including stdout and a file. However, I think this approach can't be used for formatted data as one needs to use fprintf.

Hence I am trying to come up with something similar that lets one use stdout by default and that can be switched to a file, but using the "<<" operator for formatted data.

Maybe something along the lines of

std::ostream myOutput(std::cout);

with the idea of then doing myOutput << "Hello" << 1 << 1.5;. Above line however makes the compiler complain though.

What is the correct way?

Thanks!

Cookie
  • 12,004
  • 13
  • 54
  • 83

3 Answers3

1

You could use a pointer to an std::ostream much like the FILE* version.

std::ostream* os = &std::cerr;
if (log_to_file) {
  os = new std::ofstream("my.log");
}

*os << "Hello Log!" << std::endl;

if (log_to_file) { // or less 'safe' os != &std::cerr ...
    // close file here
}
user786653
  • 29,780
  • 4
  • 43
  • 53
  • 1
    Indeed. Or even a reference, that saves dereference on output lines. – Cookie Jun 27 '11 at 13:14
  • I was going to suggest this at first, but with pointers you have the option of retargeting at runtime - for example if creating the log file fails. – user786653 Jun 27 '11 at 13:20
  • True. I have actually just run into problems trying to work with a global reference. Looks like a pointer does make more sense. – Cookie Jun 27 '11 at 13:37
1

Easy answer, really

std::ostream& myOutput(std::cout);

Thanks

Cookie
  • 12,004
  • 13
  • 54
  • 83
0

I am not quite sure I understood correctly what you're looking for. But it seems as if this one could help you:

#include <sstream>

#define SSTR( x ) ( dynamic_cast< std::ostringstream & >( \
            ( std::ostringstream() << std::dec << x ) ).str()

Usage:

SSTR( "Hello" << 1 << 1.5 );

Yields std::string (which you can then feed to whatever output function you want).

Elaborate description and explanation: http://dev.rootdirectory.de/trac.fcgi/wiki/SSTR%28%29

DevSolar
  • 67,862
  • 21
  • 134
  • 209