Operator << and easy streaming to a non-ostream class?

Hi everyone,
ok, the title is not the best one.. however, this is the thing:
I'm writing a small class to keep track of log messages from my program.
Say the class is calloed ILog. I'd love to be able to do at least one of the following:
ILog log;
int myInt=0;
log << "Hey" << " this is a message and an integer: " << myInt; // option 1
log("Hey" << "this is a message and an integer: " << myInt); // option 2

Moreover I need to pass in both cases a parameter (saying the verbosity of the message) but that should not be a problem once I can setup this first part.
I tried to have a member function which accepts an ostream object as the parameter but still I have the problem that the first object should be an ostream.
Do someone have some good ideas? I'm probably missing something stupid..
Thanks!!
Simone
hello Simone,

it is possible for option 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ILog
{
public:
  void AddStr(const std::string &str)
  {
  }
  void AddVal(const int val)
  {
  }
};

ILog &operator<<(ILog &il, const std::string &str)
{
  il.AddStr(str);
  return il;
}

ILog &operator<<(ILog &il, const int val)
{
  il.AddVal(val);
  return il;
}


option 2 would be more tricky
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct A{
    //...
    A &operator<<(const char *){
        //...
        return *this;
    }
    A &operator<<(int){
        //...
        return *this;
    }
};

//...
A log;
log <<"Hello, World!\n";
Thank you very much guys!!
Simone
Or even...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iomanip>
#include <iostream>

class Logger
{
private:
	std::ostream& os;

public:
	Logger(std::ostream& os = std::cout): os(os){}

	template<typename T>
	Logger& operator<<(const T& t)
	{
		os << t;
		return *this;
	}

	Logger& operator<<(std::ostream&(*manip)(std::ostream&))
	{
		os << manip;
		return *this;
	}
};

int main()
{
	Logger log;

	int i = 4;
	double d = 9.5;
	const char* cp = "hi de do dah";
	std::string s = "rope for mustard";

	log << i << ", " << d << ", " << cp << ", " << s << std::endl;
	log << std::hex << 123456 << std::endl;
}
4, 9.5, hi de do dah, rope for mustard
1e240
Last edited on
Topic archived. No new replies allowed.