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,570 of 33,346   
   Ulrich Eckhardt to All   
   Re: operator << overloading question   
   16 Oct 11 06:21:07   
   
   08af21fb   
   From: doomster@knuut.de   
      
   liam_herron wrote:   
   >  OStreamWrapper(int osType, const std::string& filename="")   
      
   If a constructor can be called with a single argument, you should always   
   consider making it "explicit", so it isn't accidentally called. Also,   
   osType should be an enumeration.   
      
      
   > template   
   > OStreamWrapper& operator << (OStreamWrapper& osw, const T& r)   
   > {   
   >  osw.stream() << r;   
   > }   
      
   This function is lacking a return statement.   
      
      
   > $ g++ test.cpp   
      
   Important rule: Never compile without warnings. This would probably have   
   warned you about the missing return statement in above function.   
      
      
   > test.cpp: In function =91int main()=92:   
   > test.cpp:48: error: no match for =91operator<<=92 in =91operator<< [with   
   > T = =   
   > char [17]](((OStreamWrapper&)(& os)), ((const char (&)[17])"Output to   
   > StdOut")) << std::endl=92   
      
   Please reduce your examples, remove stuff that isn't needed. This is out   
   of courtesy for your readers, but also reduces the complexity and help you   
   understand your own problem.   
      
   Now, the problem is 'os << std::endl'. The problem is that the operator<<   
   is a template _AND_ std::endl is an overloaded function. For template   
   instantiation, you need the according type. For overload resolution, you   
   need the according type. Since both depend on the other, the compiler   
   gives up, with a bad error message, actually.   
      
   Anyhow, there is a simple solution. You provide explicit non-template   
   overloads for the according overload type:   
      
   OStreamWrapper&   
   operator<<(OStreamWrapper& os, std::ostream& (*pfn)(std::ostream&))   
   {   
      os.stream() << pfn;   
      return os;   
   }   
      
   There is another one, for manipulators like std::hex, which you will also   
   come across. The solution is basically the same, but I won't spoil you the   
   fun with a read-made solution. ;)   
      
      
   Cheers!   
      
   Uli   
      
      
   --   
         [ 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