Implicit cast to bool of basic_istream/ifstream/ofstream doesn't work in Visual Studio 2013

后端 未结 3 1130
小鲜肉
小鲜肉 2021-01-14 18:26

The code below compiles in VS 2012 but not in VS 2013

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

In VS 2013 you get this compilation error:

相关标签:
3条回答
  • 2021-01-14 18:39

    If you have a lot of legacy code, you could probably add a custom operator!= (and operator==) function which takes the correct arguments:

    bool operator!=(std::basic_ios const& ios, const void* ptr);
    bool operator!=(const void* ptr, std::basic_ios const& ios);
    
    0 讨论(0)
  • 2021-01-14 18:51

    The operator is defined in section 27.5.5 Class template basic_ios.

    27.5.5.1 Overview

    explicit operator bool() const;

    And then

    27.5.5.4 basic_ios flags functions

    explicit operator bool() const;

    Returns: !fail().

    0 讨论(0)
  • C++11 requires some boolean conversions to be explicit that used to be implicit. This is noted in Appendix C about compatibility with C++03:

    C.2.15 Clause 27: Input/output library [diff.cpp03.input.output]

    27.7.2.1.3, 27.7.3.4, 27.5.5.4

    Change: Specify use of explicit in existing boolean conversion operators

    Rationale: Clarify intentions, avoid workarounds.

    Effect on original feature: Valid C++ 2003 code that relies on implicit boolean conversions will fail to compile with this International Standard. Such conversions occur in the following conditions:

    • passing a value to a function that takes an argument of type bool;
    • using operator== to compare to false or true;
    • returning a value from a function with a return type of bool;
    • initializing members of type bool via aggregate initialization;
    • initializing a const bool& which would bind to a temporary.
    0 讨论(0)
提交回复
热议问题