home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 31,610 of 33,346   
   Marc to Jerry   
   Re: rvalues and lvalues   
   03 Nov 11 16:51:44   
   
   6eea7656   
   From: marc.glisse@gmail.com   
      
   Jerry  wrote:   
      
   > How do I write a function that will accept both rvalues and lvalues?   
   >   
   > For example, if I write this (contrived example):   
   >   
   > #include    
   > #include    
   > std::vector & operator << (std::vector & x, const   
   > std::vector::value_type & y)   
   > {   
   >    x.push_back(y);   
   >    return x;   
   > }   
   > int main()   
   > {   
   >    std::cout << (std::vector() << 1)[0] << std::endl;   
   > }   
   >   
   > Then I get:   
   > Dynamo.cpp: In function 'int main()':   
   > Dynamo.cpp:12:41: error: no match for 'operator<<' in   
   > 'std::vector() << 1'   
      
   Some random ideas:   
      
   I think the best is to write 2 functions, where one (&&) forwards to   
   the other (&).   
      
   Fancier, ask as first argument a type that is constructible from   
   vector& and vector&& and stores a pointer to it (storing references is   
   asking for trouble). Sadly, even with an implicit conversion to   
   vector&, it forces you to change the code of the function.   
      
   Uglier, use templates, pass as first argument a T&&, and use sfinae to   
   restrict the possible T.   
      
   Ugliest: take a vector const& and const_cast it.   
      
   There are probably other ways...   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca