Hi all,

I've got a class which I would like to hold a stream used for logging.

The stream should be able to be set (and possibly reset) after the construction of the object.

It should be possible to set the stream as std::cout, or as a file stream to log to a file, or as a stringstream which does nothing more than ignore the data (a /dev/null of sorts). In any case, it should be an ostream type object, which the creator of the object can reset at any time. The class itself is oblivious to the concrete stream type.

I could accomplish this with a pointer to an ostream, but then the syntax becomes a little annoying, having to use the deref operator:

(*m_log) << "message";

rather than

m_log << "message";

But I can't use references, as the stream object needs to be possibly reset after the object has been initialized.

Is there an elegant way to achieve this, i.e., avoid using pointers, but still be able to reset after construction?

Thanks in advance,
Madeleine.

Recommended Answers

All 4 Replies

(*m_log) << "message; The parentheses are not necessary. Just do this: *m_log << "message";

Ancient Dragon,

yes, of course you are correct. The parentheses are not needed in that case.

But my real question is, is there a way to do this without using pointers?

Thanks,
Maddie.

You could do something like this

#include <fstream>
#include <iostream>
#include <string>

class MyClass
{
public:
	std::ostream& foo(std::ostream& stream, std::string msg);
};

std::ostream& MyClass::foo(std::ostream& stream, std::string msg)
{
    stream << msg << '\n';
	return stream;
}

int main()
{
	MyClass m;
	m.foo(std::cout, "Hello");
}

How about you make a helper function to reduce work.

class Logger{
private:
 ostream *stream;
public:
 Logger(ostream& strm) { stream = &strm; }
 void log(const std::string& msg){  _log(msg); }
private:
 void _log(const std::string& msg){ (*stream) << msg << endl; }
};

And so now you just call _log(msg) instead.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.