Explicit Conversion Operator emulation
The cxxomfort library automatically includes a header that features the ability to write explicit conversion operators for classes. The solution works by exporting a pseudo-keyword "explicit_cast
that functions as a cast operator, plus a mechanism that allows writing such operators for both C++03 and C++11-onwards - in which case it maps to native explicit operator...
.
Among other things, this enables writing classes that can convert explicitly to C++ native types such as bool (eg.: safe bool idiom) or integers (for pseudonumeric objects) in a safe and backwards-compatible way.
The solution is based off Imperfect C++'s explicit_cast
, and in fact uses the same notation.
Example usage in a class:
class MyClass { .... CXXO_EXPLICIT_OPERATOR(bool) () const { ...return a bool somehow } };
Then the object can be used and cast explicitly via explicit_cast
:
MyClass myobject; ... if (explicit_cast<bool>(myobject)) { ...do something } else { ...do something else } ...
Resulting Code
:In the case of the above code:
C++03 mode | C++11-onward mode |
---|---|
class MyClass { operator explicit_cast<bool> () const { ...return a bool somehow } } |
class MyClass { explicit operator bool () const { ...return a bool somehow } } |
if (explicit_cast<bool>(myobject)) { .... } |
if (static_cast<bool>(myobject)) { .... } |
Calling code makes use of the explicit_cast pseudo-keyword.
|
Calling code using explicit_cast translates to static_cast , for zero overhead.
|
Known limitations
This can not be used to create variables at if
-expression scopes. The solution is trivial and portable anyway - create an outer scope defined by the actual variable:
// This won't work in C++03 unless MyClass *implicitly* converts to bool if (MyClass myobject = ....) { ...} // This always work, in C++98, C++03, C++11, ... { MyClass myobject = ....; if (explicit_cast<bool>(myobject)) { .... } } // "myobject" dies at this point
explicit_cast
also always involves one copy (for the return type) in C++03. The compiler might or might not elide the resulting copy operation.
- Back to Features.