为什么这个stringstream的使用在linux上不起作用,但在Mac上运行?

Dov*_*iin 0 c++

我有这个代码将一些转换t为整数:

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

   return i;
}
Run Code Online (Sandbox Code Playgroud)

这在我的Mac上工作正常,但每当我尝试在我学校的linux机器上使用它时,它都无法编译.我必须改用这样的东西:

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

  return i;
}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.

为什么是这样?

AnT*_*AnT 5

<<std::basic_stringstreamfrom 继承的运算符std::basic_ostream返回std::basic_ostream &引用作为结果.运营商>>不适用于std::basic_ostream.出于这个原因的表达

(std::stringstream() << t) >> i
Run Code Online (Sandbox Code Playgroud)

不应该编译.

我不清楚为什么它会在你的Mac上编译.


另外需要注意的是,在预C++ 11版本的语言中

std::stringstream() << t
Run Code Online (Sandbox Code Playgroud)

对那些t依赖非成员实施的人而言,已经是不合理的operator <<.独立实现operator <<采用非const引用作为其LHS参数.