我的代码看起来像:
template <typename type> void deserialize_element(type* result) {
//...
if /*...*/
else stringstream(line) >> *result;
}
MSVC编译没有问题,但GCC给出:
error: ambiguous overload for 'operator>>' in 'std::basic_stringstream<char>(((const std::basic_stringstream<char>::__string_type&)((const std::basic_stringstream<char>::__string_type*)(& line))), std::operator|((std::_Ios_Openmode)16u, (std::_Ios_Openmode)8u)) >> * result'
/usr/include/c++/4.5/istream:120:7: note: candidates are: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>] <near match>
/usr/include/c++/4.5/istream:124:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT, _Traits>::__istream_type = std::basic_istream<char>, std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match>
现在,我在Stack Overflow和其他地方看到过类似的问题.这些似乎涉及人们继承字符串流或其他狡猾.就我而言,这应该就像应用“>>”一样简单一个普通的字符串流和一个字符?为什么这不起作用?
谢谢,
伊恩
解决方法:
我认为这个问题是MSVC如何处理rvalues的一个众所周知的错误.在线
stringstream(line) >> *result;
您正在创建临时字符串流对象,然后调用运算符>>在上面.如果运算符>>是一个*函数,它的签名可能通过引用获取stream参数.但是,临时对象(如您在此构建的对象)无法通过引用传递. Visual Studio允许您执行此操作,即使C规范不允许这样做,这就是为什么它在MSVC中有效,但g不允许这样做.
要解决此问题,请将其拆分为两行:
stringstream stream(line);
stream >> *result;
希望这可以帮助!