Dovahkiin
Dovahkiin

Reputation: 1056

How come this use of stringstream doesn't work on linux, but works on Mac?

I have this code to convert some t to an integer:

template <class T>
int toInt(const T& t)
{
  int i = -1;
  (std::stringstream() << t) >> i;

   return i;
}

This works fine on my Mac, but whenever I try to use it on the linux machines at my school, it fails to compile. I have to switch to something like this:

template <class T>
int toInt(const T& t)
{
  int i = -1;
  std::stringstream ss;
  ss << t;
  ss >> i;

  return i;
}

Which works fine.

Why is this?

Upvotes: 0

Views: 157

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320699

Operator << inherited by std::basic_stringstream from std::basic_ostream returns a std::basic_ostream & reference as result. Operator >> is not aplicable to a std::basic_ostream. For this reason the expression

(std::stringstream() << t) >> i

is not supposed to compile.

It is not immediately clear to me why it compiles on your Mac.


As an additional note, in pre-C++11 version of the language the

std::stringstream() << t

would already be ill-formed for those t that rely on non-member implementation of operator <<. Freestanding implementations of operator << take a non-const reference as their LHS parameter.

Upvotes: 5

Related Questions