Search code examples
c++templatesfriend

Friend template function specification


I have a class in which friendship with templated operator >> is established:

class MyInputStream
{
  ...
private:
   std::istream& impl;

   template<class T>
   friend MyInputStream& operator>> (MyInputStream& stream, T& outParam);
}

now I define the operator >>

   template<class T>
   MyInputStream& operator>> (MyInputStream& stream, T& outParam)
   {
       stream.impl >> outParam;
       return stream;
   }

and everything works fine.

But problem appears when I add a specialization of the template, say for "int" template argument

   template<>
   MyInputStream& operator>> (MyInputStream& stream, int& outParam)
   {
       stream.impl >> outParam;
       return stream;
   }

Then I get the link error that template operator for int is already defined in .obj file. Please advise me what should be done.


Solution

  • An explicit specialization of a function template is just like any other function, it must be defined only once.

    Either declare the specialization in a header and define it in a .cpp file, or define it as inline in the header.

    You also need to ensure that the specialization is declared before any use of the function template would cause an implicit instantiation of the function template for int. If the specialization hasn't been declared where it's needed then the primary template will be used to generate an implicit instantiation.

    (N.B. this has nothing whatsoever to do with the function being a friend, the same rules apply to all function template specializations)