In C++ is it possible to define conversion operators which are not class members? I know how to do that for regular operators (such as +), but not for conversion operators.
Here is my use case: I work with a C Library which hands me out a PA_Unichar *
, where the library defines PA_Unichar to be a 16-bit int. It is actually a string coded in UTF-16. I want to convert it to a std::string
coded in UTF-8. I have all the conversion code ready and working, and I am only missing the syntactic sugar that would allow me to write:
PA_Unichar *libOutput = theLibraryFunction();
std::string myString = libOutput;
(usually in one line without the temp variable).
Also worth noting:
I know that
std::string
doesn't define implicit conversion fromchar*
and I know why. The same reason might apply here, but that's beside the point.I do have a
ustring
, subclass ofstd::string
that defines the right conversion operator fromPA_Unichar*
. It works but this means usingustring
variables instead ofstd::string
and that then requires conversion tostd::string
when I use those strings with other libraries. So that doesn't help very much.Using an assignment operator doesn't work as those must be class members.
So is it possible to define implicit conversion operators between two types you don't control (in my case PA_Unichar*
and std::string
), which may or may not be class types?
If not what could be workarounds?