Sunday, July 12, 2009

In C++, How do I declare an overloaded extraction operator member for a template class?

Here is what I have so far, there is a prototype in the class declaration header file and here I am defining the overloaded operator. My class has two template values, but with this overloaded operator I want to send values to screen or file depending on how it's used, and return the istream object. What is the correct way to do this? Here is the incorrect way:





template %26lt;class T1, class T2%26gt;


ostream %26amp;operator%26lt;%26lt; ( ostream %26amp;strm, %26amp;kOut )


{


strm %26lt;%26lt; kOut.key %26lt;%26lt; endl %26lt;%26lt; kOut.value %26lt;%26lt; endl;


return strm;


}

In C++, How do I declare an overloaded extraction operator member for a template class?
Well, looking at your additional details, and extrapolating a little, I guess you have something like this:





template %26lt;typename T1, typename T2%26gt;


struct KeyValuePair


{


   T1 key;


   T2 value;


};





the output stream operator would thus look like this:





template %26lt;typename T1, typename T2%26gt;


std::ostream%26amp; operator%26lt;%26lt; (std::ostream%26amp; os, KeyValuePair%26lt;T1, T2%26gt; const%26amp; keyVal)


{


   return


      os %26lt;%26lt; keyVal.key


         %26lt;%26lt; std::endl


         %26lt;%26lt; keyVal.value


         %26lt;%26lt; std::endl;


}


No comments:

Post a Comment