开发者

which operator overloading has been used for ifstream object to evalute to boolean

开发者 https://www.devze.com 2023-04-07 15:02 出处:网络
I am new to C++. recently I come across the following code ifstream in(\"somefile\"); if(in){ //read the file....

I am new to C++. recently I come across the following code

ifstream in("somefile");

if(in){
    //read the file....
}

I am wondering which operator overloading the ifstream might have used for the in object to automatically evaluate to开发者_如何学C boolean in if condition. I tried but couldnt find a clue. please help me. thank in advance


It's actually operator void *.

It's overridden to return a non-zero pointer if the stream is valid, and a NULL pointer otherwise. The pointer it returns is meaningless and should not be dereferenced, it's only there to be evaluated in a boolean context.


The void pointer conversion operator is often used for this purpose. Something similar to

struct ifstream {
  typedef void * voidptr;
  operator voidptr() const;
};


std::ifstream gets its conversion to bool from it's base class std::ios (std::basic_ios<char>) which has conversion function declared:

explicit operator bool() const;

It returns !fail().

(In the previous version of the standard ISO/IEC 14882:2003, std::basic_ios had a conversion function operator void*() const but this version of the standard has now been withdrawn.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号