The C++11 std::function
is supposed to implement operator bool() const
, so why does clang tell me there is no viable conversion?
#include <functional>
#include <cstdio>
inline double the_answer()
{ return 42.0; }
int main()
{
std::function<double()> f;
bool yes = (f = the_answer);
if (yes) printf("The answer is %.2f\n",f());
}
The compiling error is:
function_bool.cpp:12:7: error: no viable conversion from 'std::function<double ()>' to 'bool'
bool yes = (f = the_answer);
^ ~~~~~~~~~~~~~~~~
1 error generated.
EDIT I didn't see the explicit
keyword.. no implicit conversion then, I guess I'll have to use static_cast
.
operator bool()
forstd::function
isexplicit
, therefore it cannot be used for copy-initialization. You can actually do direct-initialization:However, I assume it's really intended for contextual conversion, which happens when an expression is used as a condition, most often for an
if
statement. Contextual conversion can callexplicit
constructors and conversion functions, unlike implicit conversion.