4

I have to use an explicit specialization for a class member function in (C++ , I am using MS Visual Studio 2008 SP1), but I could not success to compile it. Getting

error C2910: 'File::operator <<' : cannot be explicitly specialized

class File
{
   std::ofstream mOutPutFile;
public:
   template<typename T>
   File& operator<<(T const& data);
};


template<typename T>
File& File::operator<< (T const& data)
{
    mOutPutFile << preprosesor(data);
    return *this;
}

template< >
File& File::operator<< <> (std::ofstream& out)
{
   mOutPutFile << out;
   return *this;
}
Agus
  • 1,604
  • 2
  • 23
  • 48
  • http://stackoverflow.com/search?q=%5BC%2B%2B%5D+specialize+member+function – Mooing Duck Apr 23 '12 at 14:09
  • You're working on Windows; the version of MSVC might be relevant. It often helps people give better answers if you give that sort of information. – Jonathan Leffler Apr 23 '12 at 14:10
  • 1
    possible duplicate of [Function template specialization format](http://stackoverflow.com/questions/937744/function-template-specialization-format) – Jonathan Leffler Apr 23 '12 at 14:12
  • 1
    Your question is already answered by Andrey. On top of that you can think of having a *function overload* rather than *function specialization*. That will be simpler. – iammilind Apr 23 '12 at 14:15

1 Answers1

6

Your explicit specialization of operator << didn't match the parameter list of the declaration; T const& data vs std::ofstream& out. This one compiles in MSVC10.

template<>
File& File::operator<< <std::ofstream> (const std::ofstream& out)
  {
  mOutPutFile << out;
  return *this;
  }

Notice const added before the function parameter.

Andriy
  • 8,486
  • 3
  • 27
  • 51
  • Note that the ofstream here is an rvalue - it appears on the right side of << in usage. When you define (global) operator<< the ostream must be non-const to actually compile. That's not a problem here. – emsr Apr 23 '12 at 14:51
  • It's mOutPutFile, not std::ofstream& out, which is written to here. – Andriy Apr 23 '12 at 15:26