给定Objective-C类型type
,可以轻松获得该类型的encoding encoding
和大小size
:
const char *encoding = @encode(type);
size_t size = sizeof(type);
换一点点,我们有映射
@encode: type_t -> const char *
sizeof: type_t -> size_t
这提出了两个问题:
(1)假设我们只有一个编码,而不是一个类型。获得映射
会很不错sizeofencodedtype: const char * -> size_t
这样,对于每个 type_t type
我们都有
sizeofencodedtype(@encode(type)) = sizeof(type)
这样的功能是否已经存在?如果没有,怎么可能建立一个?
(2)理想情况下,我们可以反转 @encode 映射来进行映射
decode: const char * -> type_t
但这似乎不可能,因为 type_t 不是真正的C类型。我想我可以等待 @decode 添加到语言中,但这不是很现实或时间敏感。但是,如果不能使用其编码在运行时实例化类型吗?
参考文献: Objective-C Runtime Programming Guide - Type Encodings