加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 对basic_istream / ifstream / ofstream的bool进行隐式强制

发布时间:2020-12-16 09:51:54 所属栏目:百科 来源:网络整理
导读:以下代码在VS 2012中编译,但在VS 2013中编译 std::ofstream stm;if(stm != NULL){} 在VS 2013中,您收到此编译错误: binary ‘!=’ no operator found which takes a left-hand operand of type ‘std::ofstream’ (or there is no acceptable conversion)
以下代码在VS 2012中编译,但在VS 2013中编译

std::ofstream stm;
if(stm != NULL)
{
}

在VS 2013中,您收到此编译错误:

binary ‘!=’ no operator found which takes a left-hand operand of type ‘std::ofstream’ (or there is no acceptable conversion)

我查看了标题,并在< xiobase>中我找到了以下内容:

VS2012

ios_base::operator void *() const;

VS2013

operator void *()const已被删除,并且添加了带有显式的运算符bool:

ios_base::explicit operator bool() const;

现在我的问题:

>我在互联网上找不到有关此更改的任何信息.你知道在任何地方都有关于这种变化的官方文章吗?
>我有遗留代码,其中if(stm!= NULL)被大量使用.出于无关的原因,最好不要更改代码.有没有办法让它在VS 2013中编译而不改变它?我找不到任何可以恢复operator void *或从运算符bool()中删除显式的条件编译指令.

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,char_traits<char>> &stm)
{
    return !operator==(stm,null_val);
}

bool operator!=(const std::basic_ios<char,int null_val)
{
    return !operator==(stm,null_val);
}

在我的情况下,char值类型足够,第二个参数是int,因为不支持非NULL的东西.

解决方法

如果你有很多遗留代码,你可以添加一个自定义运算符!=(和operator ==)函数,它接受正确的参数:

bool operator!=(std::basic_ios const& ios,const void* ptr);
bool operator!=(const void* ptr,std::basic_ios const& ios);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读