Reputation: 7933
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
.
Upvotes: 2
Views: 1752
Reputation: 119069
operator bool()
for std::function
is explicit
, therefore it cannot be used for copy-initialization. You can actually do direct-initialization:
bool yes(f = the_answer);
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 call explicit
constructors and conversion functions, unlike implicit conversion.
// this is fine (although compiler might warn)
if (f = the_answer) {
// ...
}
Upvotes: 7