I have the following code, which uses a Unicode string class from a library that I’m writing:
#include <cstdio>
#include "ucpp"
main() {
ustring a = "test";
ustring b = "ing";
ustring c = "- -";
ustring d;
d = "cafe\xcc\x81";
printf("%s\n", (a + b + c[1] + d).encode());
}
The encode method of the ustring class instances converts the internal Unicode into a UTF-8 char *. However, because I don’t have access to the char class definition, I am unsure on how I can define an implicit typecast (so that I don’t have to manually call encode when using with printf, etc).
First, I would recommend that you consider not providing an implicit conversion. You may find that the situations where unexpected conversions are not caught as errors outweighs the cost of calling
encodewhen you want achar*.If you do decide to provide an implicit conversion you declare it like this (inside your class definition.
You might be able to make the method const, in which case you can use:
Usually you would also want to return a pointer to a non-modifiable buffer:
In the body of your function you should
returnan appropriate pointer. As an implicit conversion clients wouldn’t expect to have to free the returned buffer so if you need to make a special buffer for your return value you will have to maintain a pointer to this buffer until a suitable point to free it. Typically such a suitable moment might be the next mutating operation on your class object.Note that as
printftakes any number and type of optional arguments you would still need to cast your class object in any case.or
Both of these are more verbose than an explicit call to
encode.