"If (getline (fin, str)) {}" conforms to the C ++ 11 standard?

I checked the C ++ 11 standard and found the following facts:

  • std::getline(fin, str) returns a basic_ios object whose class has a member function explicit operator bool() const;

  • The basic_ios class basic_ios not have a member function operator void*() const; like pre-c ++ 11.

So, I think that if (getline(fin, str)) {} not standard. It should be written as

if (bool(getline(fin, str)){} . (However, VC ++ 2012 gives a warning about this use, i.e. Force void * to bool)

Am I right?

+7
source share
3 answers

David is right, and here are quotes to support him. Section 12.3.2 / 2 of the Standard states:

The transformation function can be explicit (7.1.2), in which case it is only considered as a user-defined transformation for direct initialization (8.5). Otherwise, user transformations are not limited to use in assignments and initializations. [Example:

 class Y { }; struct Z { explicit operator Y() const; }; void h(Z z) { Y y1(z); // OK: direct-initialization Y y2 = z; // ill-formed: copy-initialization Y y3 = (Y)z; // OK: cast notation } 

- end of example]

In some places where this contextual transformation takes place, it is in the operand ! , operands before && and if condition.

So direct initialization can use explicit conversion operators , and in Β§4 / 3,

An expression e can be implicitly converted to type T if and only if the declaration T t=e; well formed, for some invented time variables, the variable t (8.5). Some language constructs require that the expression be converted to a Boolean value. The expression e appears in such a context, as they say, is contextually converted to bool and is well-formed if and only if the declaration bool t(e); well formed , for some invented time variable T (8.5) ...

So, as you can see, the standard specifies how direct initialization is for contextual transformations, so why explicit conversions work under if conditions.

+6
source

The code matches. The explicit conversion operator to bool is called when the object is used as a condition automatically. Changing the standard meant supporting the same use, making it safer.

+12
source

explicit operator bool (and only explicit operator bool ) has a special language that allows in certain circumstances to implicitly convert it to bool . The specification language for this conversion is "context-converted to bool ".

These are the places where the language performs logical testing. The conditional expression used by if/while/for is "context converted to bool ". Like logical operators and conditional operator ( ?: .

So, while you cannot do this:

 bool b = std::getline(fin, str); void func(bool) {} func(std::getline(fin, str)); 

You can do it:

 while(std::getline(fin, str)) {...} for(;std::getline(fin, str);) {...} if(std::getline(fin, str) && somethingElse) {...} 
+8
source

All Articles