c++ - operator<< working w/ temp variable, but not directly with function call -


i'm trying write std::ostream operator<< class. have function (taking advantage of rov) returns instances of class.

my operator works when assign result of function call local variable, , pass local operator <<, not when pass result in directly. what's going on here?

simplified standalone example (test.cpp):

#include <iostream>  template <class t> class anobject{ public:    anobject(t value) : m_value(value) {}   t getvalue(){ return m_value; } protected:   t m_value; };  template <class t> std::ostream & operator<<(std::ostream& os, anobject<t> & obj ) {   os << obj.getvalue();   return os; }  anobject<int> getobject() {   return anobject<int>(5); }  int main(int argc, char**argv) {   // doesn't compile   std::cout << getobject() << std::endl;    // does....   //auto obj = getobject();   //std::cout << obj << std::endl; } 

compiler command (g++ version 4.8.4 on ubuntu):

g++ -std=c++11 test.cpp

error:

test.cpp:26:26: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue ‘std::basic_ostream<char>&&’ 

anobject<int> getobject() {   return anobject<int>(5); } 

this function above error. why? because it's used part of rvalue expression, not lvalue.

in c++, lvalues sort of represent "containers" hold actual values. rvalues refer these "actual" values. example:

int = 5; // lvalue, 5 rvalue. // 5 not variable, has rvalue of 5 lvalue of i. 

the << operators wants actual object instead of value of it--in other words, should have "home" , stored somewhere.

so either make overload takes &&, means can take values may not "live" anywhere (e.g. expressions) or require values come in lvalues (references real objects). option use const t&, rvalues can cast.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -