运算符优先级更改

cup*_*cup 1 c++ visual-studio-2008 visual-studio-2013

以下用于在VS2008上构建OK,但在VS2013上,它呻吟.好吧用g ++.

#include <sstream>
int main()
{
    int a = 2, b = 5;
    std::ostringstream oss;

    oss << a == 0 ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

错误消息是

1>u:\precedence\precedence.cpp(7): error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::basic_ostream<char,std::char_traits<char>>' (or there is no acceptable conversion)
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(497): could be 'bool std::operator ==(const std::exception_ptr &,const std::exception_ptr &)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(502): or       'bool std::operator ==(std::nullptr_t,const std::exception_ptr &)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\exception(507): or       'bool std::operator ==(const std::exception_ptr &,std::nullptr_t)' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\system_error(402): or       'bool std::operator ==(const std::error_code &,const std::error_condition &) throw()' [found using argument-dependent lookup]
1>          c:\program files\microsoft visual studio 12.0\vc\include\system_error(410): or       'bool std::operator ==(const std::error_condition &,const std::error_code &) throw()' [found using argument-dependent lookup]
1>          while trying to match the argument list '(std::basic_ostream<char,std::char_traits<char>>, int)'
Run Code Online (Sandbox Code Playgroud)

如果输出语句更改为,则它适用于两个版本

    oss << (a == 0? a: b);
Run Code Online (Sandbox Code Playgroud)

如果不使用常量,我可以在VS2008中强制执行不同的错误:类似于

int zero = 0;
oss << a == zero? a: b;
Run Code Online (Sandbox Code Playgroud)

只是想知道为什么没有使用常量时会出现错误.

编辑托管以使用-Wall使用g ++发出警告.

chr*_*ris 7

在所有情况下,编译器由于优先级而看到的表达式是:

((oss << a) == 0) ? a : b;
Run Code Online (Sandbox Code Playgroud)

现在oss << a回来了oss.你如何oss与0 比较?它有一个隐式转换运算符operator void *.

VS2013可能会替换explicit operator bool为C++ 11(其中的重点是这些难以发现的错误不会发生).根据我的知识,libstdc ++还没有完成这个替换.它必须符合C++ 11.

现在为什么不zero编译?zero不是空指针常量,而是0.因此,后者可以与返回的指针进行比较operator void *.

在任何情况下,修复此问题的简单方法是使其适用于任何符合要求的实现,即添加括号:

oss << (a == 0 ? a : b);
Run Code Online (Sandbox Code Playgroud)