Ambiguous overload for string flow

My code looks something like this:

template <typename type> void deserialize_element(type* result) {
    if /*...*/
    else stringstream(line) >> *result;


MSVC compiles without issue, but GCC gives:

    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>


Now, I've seen some similar questions here on Stack Overflow and elsewhere. They seem to be dealing with people subclassing stringstream or other tricks. As far as I know, this should be as simple as applying "→" to regular string strings and char? Why doesn't it work?



source to share

1 answer

I think the problem is a known bug in the way MSVC ++ handles rvalues. In line

stringstream(line) >> *result;


A temporary object stringstream

is created and then called operator >>

. If operator >>

is a free function, its signature probably takes a stream parameter by reference. However, temporary objects like the one you created here cannot be passed by reference. Visual Studio allows you to do this even though it is not allowed by the C ++ spec, so it works in MSVC, but g ++ doesn't allow it.

To fix this, split it into two lines:

stringstream stream(line);
stream >> *result;


Hope this helps!



All Articles