【发布时间】:2014-04-23 06:31:50
【问题描述】:
以下代码在 VS 2012 中编译,但在 VS 2013 中不编译
std::ofstream stm;
if(stm != NULL)
{
}
在 VS 2013 中,您会收到以下编译错误:
二进制 '!=' 未找到接受 'std::ofstream' 类型左侧操作数的运算符(或没有可接受的转换)
我查看了标题并在<xiobase> 中发现了以下内容:
VS2012
ios_base::operator void *() const;
VS2013
operator void *() const 已被删除,而是添加了带显式的运算符 bool:
ios_base::explicit operator bool() const;
现在我的问题:
- 我在 Internet 上找不到有关此更改的任何信息。您是否知道任何地方是否有关于此更改的官方文章?
- 我有很多使用 if(stm != NULL) 的遗留代码。由于不相关的原因,最好不要更改代码。有没有办法让它在 VS 2013 中编译而不改变它?我找不到任何可以恢复运算符
void*或从运算符 bool() 中删除explicit的条件编译指令。
PS:gcc 4.9.0 仍然有operator void*() const。所以就不会有这个问题了。
更新:
为了编译我的遗留代码,我按照建议实现了以下重载:
#include <xiosbase>
bool operator==(const std::basic_ios<char, char_traits<char>> &stm, int null_val)
{
return static_cast<bool>(stm) == null_val;
}
bool operator==(int null_val, const std::basic_ios<char, char_traits<char>> &stm)
{
return operator==(stm, null_val);
}
bool operator!=(int null_val, const std::basic_ios<char, char_traits<char>> &stm)
{
return !operator==(stm, null_val);
}
bool operator!=(const std::basic_ios<char, char_traits<char>> &stm, int null_val)
{
return !operator==(stm, null_val);
}
在我的情况下,char 值类型就足够了,第二个参数是 int,因为无论如何都不支持非 NULL 的东西。
【问题讨论】:
-
这个变化是 C++11 规范的一部分,所以应该很容易找到关于它的文章。如果没有别的,请阅读规范草案。
-
@JoachimPileborg 是的,en.cppreference.com/w/cpp/io/basic_ios/operator_bool 是一篇非常有用的文章。它说 operator void *() "直到 C++11" 和显式 operator bool() "since C++11"。所以看起来这是一个已知的变化
-
我怀疑 GCC 4.9 的 libstdc++ 在 C++11 模式下编译时有
operator void*。我在the GCC 4.9ostreamheader 中找不到它,其中包含operator bool... -
@rubenvb 看这个演示goo.gl/yIHOXx
-
嗯,这看起来是错误的... C++11
27.5.5.1在std::basic_ios中没有operator void*() const。但是VS2013 still has it,尽管它们显示了一个获取流对象地址的示例。
标签: c++ visual-studio-2012 c++11 visual-studio-2013