im having an issue with the ostream, I have written a very basic macro that should print out its parameters.
Please see example code below:
#define LOG Message(__FILE__, __LINE__,__func__)
class Message : public std::ostringstream
{
public:
Message(const char *param1, int param2, const char *param3)
{
*this<<param3<<"("<<param1<<":"<<param2<<")";
}
~Message()
{
*this<<endl;
cout<< rdbuf()->str();
}
};
int main()
{
int integer = 1;
string str = "XYZ";
LOG<<integer<<"DEBUGLOG1: "<<str<<" "<<integer;
return 0;
}
The problem is if I use:
LOG << "LOG1: " << str << " " << integer;
The output prints the Address* of the const char* "LOG1: " rather than the value.
But, If I use:
LOG << integer << "DEBUGLOG1: " << str << " " << integer;
The output works perfect, printing the integer value and the char value.
it looks like instead of using ostream& operator<< (ostream& out, const char* s );
it is using ostream& operator<< (const void* val);
?
Can anyone shed any light on what can be done to overcome this overloading please?
Thanks in advance
The problem is that Message(...)
is a temporary. The temporary cannot bind to a non-const reference parameter for operator<<
.
It can only be used with member functions and operators, like ostream::operator<<(int)
.
The odd thing is that the member operator returns a reference which can, in turn, be used with the non-member operators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With