4

我必须在(C++,我正在使用MS Visual Studio 2008 SP1)中为类成员函数使用显式专用化,但是我无法成功编译它。获得成员函数的模板专门化

错误C2910: '文件::运算< <':不能明确专门

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; 
} 
+0

http://stackoverflow.com/search?q=%5BC%2B%2B%5D+specialize+member+function – 2012-04-23 14:09:55

+0

您正在使用Windows; MSVC的版本可能是相关的。如果您提供这类信息,它通常会帮助人们给出更好的答案。 – 2012-04-23 14:10:09

+1

[函数模板专业化格式]的可能重复(http://stackoverflow.com/questions/937744/function-template-specialization-format) – 2012-04-23 14:12:36

回答

5

您的运营< <没有声明的参数列表相匹配的明确分工; T const& data vs std::ofstream& out。 这个编译MSVC10。

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

通知const在函数参数之前添加。

+0

请注意,这里的流是一个右值 - 它出现在<<的使用中的右侧。在定义(全局)运算符<<时,ostream必须是非const才能真正编译。这在这里不是问题。 – emsr 2012-04-23 14:51:30

+0

它是mOutPutFile,而不是std :: ofstream&out,写在这里。 – Andrey 2012-04-23 15:26:37