he compiler invokes user-defined conversion functions (which are also called conversion operators) implicitly. In most cases, this process is well-behaved and intended. However, there are cases when you certainly don't want the compiler to invoke the conversion operator implicitly—but you can't prevent it. Several workarounds have been devised to mitigate this problem, including the indirect conversion idiom. And yet, these workarounds are neither intuitive nor perfect. C++0x finally brings a radical solution in the form of explicit conversion functions.
Your class defines a conversion function to a certain type. You want to ensure that this function will be invoked only when appropriate.
Declare conversion functions explicit, thus forcing clients to use casts explicitly.
Presenting the Problem
The problematic nature of unrestrained conversion functions is clearly demonstrated in smart pointers. Class std::shared_ptr defines an implicit conversion to an implementation-defined Boolean type. As you may recall, the "implementation-defined Boolean type" is actually a pointer to a data member, not the built-in booltype:
template <class T>
operator PtrConversion::*pmi() const//Boolean conversion
return rawptr? &PtrConversion::valid : 0;
As ugly as this kludge may seem, it does prevent awful bugs like these:
Ptr p1, p2;
cout<<"p1 + p2 = "<< p1+p2 <<endl;
Ptr <File> pf;
Ptr <Query> pq; //Query and File are unrelated types
if(pf==pq)... //compares raw pointers, not objects!
There are, however, other ailments that the indirect conversion idiom cannot cure.