C ++ custom conversion operators without classes?

In C ++, can I define conversion operators that are not members of a class? I know how to do this for regular operators (e.g. +), but not for conversion operators.

Here is my use case: I am working with a C library that tells me PA_Unichar *where the library defines PA_Unichar as a 16-bit int. This is actually a string encoded in UTF-16. I want to convert it std::stringto UTF-8 encoded. I have conversion code ready and working and I just skip the syntactic sugar that would let me write:

PA_Unichar *libOutput = theLibraryFunction();
std::string myString = libOutput;

(usually in one line without temp variable).

Also worth noting:

  • I know that it std::stringdoes not define an implicit conversion from char*, and I know why. The same reason can be applied here, but this is not relevant.

  • I have a ustringsubclass std::stringthat defines the correct conversion operator from PA_Unichar*. It works, but that means using variables ustringinstead std::string, and then requires conversion to std::stringwhen I use these lines with other libraries. So it doesn’t help much.

  • Using an assignment operator does not work, since they must be members of the class.

Thus, you can define implicit conversion operators between two types that you do not control (in my case PA_Unichar*and std::string), which may or may not be class types?

?

+5
4

?

std::string convert(PA_Unichar *libOutput);

std::string myString = convert(theLibraryFunction());

:

DrPizza : , , " ".

: . , rvalue, std::string , . , .

+8

- , . .

+5

, "" . , conversion functions special member functions. , :

struct mystring : public string
{
    mystring(PA_Unichar * utf16_string)
    {
        // All string functionality is present in your mystring.
        // All what you have to do is to write the conversion process.
        string::operator=("Hello World!");
        string::push_back('!');
        // any string operation...
    }
};

, . string*, ! , :

mystring str(....);

, !

string* str = new mystring(....);
....
delete str; // only deleting "string", but not "mystring" part of the object
// std::string doesn't define virtual destructor
+4

No, you can’t. Alternatively, you can create a conversion constructor in the target class (not your case, since you want to convert it to std :: string), unless you print it). But I agree with the other answers, I think that implicit conversion is not recommended in this case - especially because you are not converting it from an object, but from a pointer. It is better to have a free function, your code will be easier to understand, and the next programmer who inherits the code will certainly thank you.

+3
source

All Articles