PPP Chapter 12 Converting ifstream to bool

Hello, I am currently almost finished with the task of setting up FLTK for the book Programming Principles and practice.

I have sucessfully installed FLTK 1.1.9(Tested to see if it works), and I have properly put all the headers and cpp files into a project, which is supposed to make a triangle appear on the screen.

There is 2 errors that I get, and that is:
1
2
3
4
43 error C4616: 'Graph_lib::can_open':must return a value


44 IntelliSense: no suitable conversion function from "std::ifstream" to "bool" exists


Here is the code, where the error appears. It is located in Graph.cpp:

1
2
3
4
5
6
7
8
9
10
//----------------------------------------------------------------------

bool can_open(const string& s)
	// check if a file named s exists and can be opened for reading
{
	ifstream ff(s.c_str());
	return ff;
}

//----------------------------------------------------------------------- 

Please help me.
Last edited on
Visual Studio issues. Use return static_cast<bool>(ff);. This should help.
Many thanks!
> no suitable conversion function from "std::ifstream" to "bool" exists
>> Visual Studio issues.

There would be an error with any conforming C++11 implementation.

There is no implicit conversion from a C++ stream to bool
explicit operator bool() const;
http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool


As far as this error goes, the GNU implementation (libstdc++) is non-conforming.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int foo() 
{ 
    if( std::cin ) // fine; stream is used in a bool context
                   // explicit operator bool() const is called     
        return 100 ; 
    else 
        return -1 ; 
}

bool bar() 
{ return std::cin ; } // *** error: no implicit conversion from std::cin to bool

const void* baz() 
{ return std::cin ; } // *** error: no implicit conversion from std::cin to const void* 

http://coliru.stacked-crooked.com/a/d3fbd177c706348c
I always thought that return will try to explicitely convert value to needed type.

Thanks for clarifying.
Topic archived. No new replies allowed.