MyLogger inflog(LOG_INFO);
inflog << ": This has no problem";
MyLogger(LOG_ERROR) << ": But this does not work";

My brain is tingling about r-value's but I can't seem to find anything that really makes sense. It is not like the second version creates a constant MyLogger -- But for some reason or another the compiler can't make a copy to pass to the function.

Side Note: The code is actually better with the const in -- I am just trying to understand WHY it is needed.

Re: Non-matching template error

Posted 15 March 2011 - 12:02 PM

The only thing I can think of is the possibility that you are returning a const reference from the temporary object. I found this link and by changing your class and the #define I was able to compile and run your program without the constant. I added MyLogger& ref() { return *this;} to your class and changed the #define to #define LOG(level) (MyLogger(level).ref()) << ": " __FILE__ << "(" << __LINE__ << "): ", and removed the const qualifier ostream& operator<<( MyLogger &mlog, const T& data){ .

Re: Non-matching template error

My initial error was triggered because an rvalue (temporary variable) can not be implicitly bound to a modifiable lvalue. Consider this bit of code:

void foo(int& arg) { arg++; }
...
i = 0;
foo(i++);
cout << i;

What value gets displayed? Well we are tying to pass i before it gets incremented, which is an rvalue (a temporary value of an expression) and it has no address to "reference". This kind of thing is not allowed because the temporary value is not guaranteed to have an address and it will cease to exist at the end of the expression and so even if there were an address (the compiler will make one if it needs one) assigning that address to anything persistent(an lvalue) is dangerous.

However if the compiler knows that the rvalue will not be modified it can make a persistent copy.

Of course if you really want to force the compiler to give you an address you can. This becomes important when you are dealing with objects which may have side-effects that require the internal state of the object to change. SO there are work arounds that let you explicitly ask for a reference (thus your example).

Now I am only been ruminating on this information for a few hours between work and "having a baby school" so I may not have fully grasped the deeper nature here.