为了序列化任何对象(即对于没有全局ostream& operator<<
的对象,字符串为空),我创建了一个函数,该函数利用了std::ostream& operator<<
来自单独命名空间的重载;
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;
}
这适用于我尝试过的所有类型,除了 char 的 operator<< 被认为是模棱两可的。我不明白为什么它适用于 int's、short's 或任何其他定义了运算符的类型,但不适用于 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 ==========