如何定义从类到标量的隐式类型转换?
我有以下代码,它使用我正在编写的库中的 Unicode 字符串类:
#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());
}
ustring 类实例的encode 方法将内部 Unicode 转换为 UTF-8 char *。但是,因为我无权访问 char 类定义,所以我不确定如何定义隐式类型转换(以便在与 printf 等一起使用时不必手动调用编码)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我建议您考虑不提供隐式转换。您可能会发现,当您需要
char*
时,意外转换未被捕获为错误的情况比调用encode
的成本更重要。如果您确实决定提供隐式转换,则可以像这样声明它(在类定义中)。
您也许可以将该方法设置为 const,在这种情况下您可以使用:
通常您还希望返回一个指向非可修改的缓冲区:
在函数主体中,您应该
返回
一个适当的指针,因为隐式转换客户端不会期望必须释放返回的缓冲区,因此如果您需要为您的函数创建一个特殊的缓冲区。返回值,您必须维护指向此缓冲区的指针,直到有合适的点来释放它。通常,这样的合适时刻可能是类对象上的下一个变异操作。请注意,因为 printf 可以采用任何数字。以及在任何情况下您仍然需要转换类对象的可选参数的类型,
或者
这两者都比显式调用
encode
更详细。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
encode
when 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
return
an 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
printf
takes 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
.