2013-04-15 143 views
2

爲了序列化任何對象(即,對於沒有全局對象的對象,字符串爲空),我創建了一個函數其利用來自單獨名稱空間的過載std::ostream& operator<<;std :: ostream&operator <<(std :: ostream&sstr,const T&val)的模糊重載

namespace _impl { 
template <typename T> 
std::ostream& operator<<(std::ostream& osstr, const T& val) { 
    return osstr; 
} 
} 

template <typename T> 
std::string serialize_any(const T& val) { 
    using namespace _impl; 
    std::ostringstream osstr; 
    osstr<< val; 
    std::string str(osstr.str()); 
    return str; 
} 

這適用於所有類型的我試過,除了燒焦的地方運營商< <被認爲是不明確的。 我不明白爲什麼它適用於int,short或任何其他運算符定義的類型,但不適用於chars。有人有主意嗎?

1>application_src\general_experiments.cpp(39): error C2593: 'operator <<' is ambiguous 
1>   application_src\general_experiments.cpp(26): could be 'std::ostream &_impl::operator <<<T>(std::ostream &,const T &)' 
1>   with 
1>   [ 
1>    T=char 
1>   ] 
1>   C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\ostream(914): or  'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,_Elem)' [found using argument-dependent lookup] 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
1>   C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\ostream(827): or  'std::basic_ostream<_Elem,_Traits> &std::operator <<<std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup] 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
1>   C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\ostream(742): or  'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char_traits<char>>(std::basic_ostream<_Elem,_Traits> &,char)' [found using argument-dependent lookup] 
1>   with 
1>   [ 
1>    _Elem=char, 
1>    _Traits=std::char_traits<char> 
1>   ] 
1>   while trying to match the argument list '(std::ostringstream, const char)' 
1>   application_src\general_experiments.cpp(52) : see reference to function template instantiation 'std::string serialize_any<char>(const T &)' being compiled 
1>   with 
1>   [ 
1>    T=char 
1>   ] 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 
+2

[這](http://stackoverflow.com/questions/16015051)是* *原因...雖然這不是一個解決方案。 :( –

回答

1

編譯器似乎從const char&鑄造的地方char在同一水平向上轉型std::ostringstreamstd::ostream當過載分辨率的問題。

的解決方案可以是模板的operator<<類型以避免向上轉型:

namespace _impl { 
    template <typename T, typename Y> 
    Y& operator<<(Y& osstr, const T& val) { 
     return osstr; 
    } 
} 
+0

沒有工作,編譯器似乎優先於所有其他運營商 –

相關問題