Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I return std::getline's as-if-boolean result?

A standard idiom is

while(std::getline(ifstream, str))
    ...

So if that works, why can’t I say

bool getval(std::string &val)
{
    ...

    std::ifstream infile(filename);

    ...

    return std::getline(infile, val);
}

g++ says "cannot convert 'std::basic_istream<char>' to 'bool' in return".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is the Boolean context of a return statement in a bool-valued function somehow different from the Boolean context of while(), such that the magic conversion that std::basic_istream performs in one context doesn’t work in the other?

>Solution :

The boolean conversion operator for std::basic_istream is explicit. This means that instances of the type will not implicitly become a bool but can be converted to one explicitly, for instance by typing bool(infile).

Explicit boolean conversion operators are considered for conditional statements, i.e. the expression parts of if, while etc. More info about contextual conversions here.

However, a return statement will not consider the explicit conversion operators or constructors. So you have to explicitly convert that to a boolean for a return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading