conversion operator as standalone function

c++, conversion-operator, type-conversion

Solution

The one reason I can think of is to prevent implicit conversions being applied to the thing being cast. In your example, if you said:

 bool( "foo" );

then "foo" would be implicitly converted to a string, which would then have the explicit bool conversion you provided applied to it.

This is not possible if the bool operator is a member function, as implicit conversions are not applied to `*this`. This greatly reduces the possibilities for ambiguity - ambiguities normally being seen as a "bad thing".

Problem

Why does C++ require that user-defined conversion operator can only be non-static member? Why is it not allowed to use standalone functions as for other unary operators? Something like this: ``` operator bool (const std::string& s) { return !s.empty(); } ```

Original source

Related problems