Why the code does not compile.
Operator
std::shared_ptr conversion-to- bool declared explicit and therefore will usually not be called for implicit conversion.
In particular, it will not be called in the context of the return .
And this will not be considered for the selection of the overload function, i.e. foo(p) will not allow overloading foo , which takes a bool argument.
However, there are many ways to express explicitly, including:
!!ptr ptr != nullptr ptr.get() != nullptr static_cast<bool>( ptr ) ptr.operator bool()
General case for implicit conversion to bool .
There are cases when explicit on operator bool() ignored in order to make the work work mainly as in C ++ 03. That is, everything works the same way as with the explicit schemes used earlier for conversion operators in C ++ 11. These exceptions:
use as a condition (for grammar) in if , while or for , but not in switch ,
use as condition in :? selecting static_assert or noexcept ,
use the built-in logical operators && , || as an argument and ! or their equivalents and , or and not .
It is noteworthy that these exceptions, which allow an implicit conversion to bool , despite explicit , called contextual transformations , do not include the expression of the return .
Is it possible to ignore explicit in other cases?
In what other cases, if any, can explicit ignore the conversion operator?
Well no. But the conversion operator is not explicit , i.e. An implicit conversion operator can be invoked implicitly where the exact type to be converted is not specified by the context.
C ++ 11 §4 / 5 (conv):" . For some language constructs, conversion to a value corresponding to one of the specified set of types to the construction is required. An expression e type of class e appearing in such a context is called contextually implicitly converted to the specified type T and is well formed if and only if e It can be converted implicitly to a type T , which is defined as follows: e is searched transformation functions, which is a return type cv T , or a reference to cv T , for which T is enabled context there must. It is exactly one such T .
For example,
C ++ 11 §5.3.5 / 1 (expr.delete):" If the type is a class, the operand [from delete ] is contextually implicitly converted (section 4) to an object type pointer.
& hellip; and therefore, a little intuitive to me, the following should compile with the appropriate compiler:
struct Foo { operator int*() const { return nullptr; } }; auto main() -> int { delete Foo(); }