Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC compiler error when extracting a char from a temporary stream

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:

  • Visual Studio 2008 compiles without errors
  • Other types (int, double) are working
  • If I first create a variable std::istringstream iss("a"); iss >> c, the compiler gives no error
like image 870
Christian Ammer Avatar asked Jan 25 '12 14:01

Christian Ammer


1 Answers

The 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.

like image 119
Mike Seymour Avatar answered Sep 30 '22 13:09

Mike Seymour