I'm trying to read a single character from a stream. With the following code I get a "ambiguous overload" compiler error (GCC 4.3.2, and 4.3.4). What I'm doing wrong?
#include <iostream>
#include <sstream>
int main()
{
char c;
std::istringstream("a") >> c;
return 0;
}
Remarks:
int
, double
) are workingstd::istringstream iss("a"); iss >> c
, the compiler gives no errorThe extraction operator >>
for characters is a non-member function template:
template<class charT, class traits>
basic_istream<charT,traits>& operator>>(basic_istream<charT,traits>&, charT&);
Since this takes its first argument by non-const
reference, you can't use a temporary rvalue there. Therefore, your code cannot select this overload, only the various member function overloads, none of which match this usage.
Your code is valid in C++11, because there is also an extraction operator taking an rvalue reference as the first argument.
Visual Studio 2008 compiles without errors
One of that compiler's many non-standard extensions is to allow temporary rvalues to be bound to non-const
references.
Other types (
int
,double
) are working
Most extraction operators for fundamental types are member functions, which can be called on a temporary rvalue.
If I first create a variable
std::istringstream iss("a"); iss >> c
, the compiler gives no error
iss
is a non-temporary lvalue, so it can be bound to a non-const
reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With