Kus*_*alP 3 objective-c objective-c++ core-foundation
有没有一种简单的方法将 a 转换CTypeRef为特定的 CoreFoundation 类型?我不想进行内联转换,(CFStringRef)myObjectRef但想创建一个辅助方法来为所有 CoreFoundation 类型执行此操作。
我知道可以使用类似的方法CFGetTypeID(myObjectRef) == CFStringGetTypeID()来确定 a 是否CTypeRef是 a CFString。然而,创建单个方法来执行此操作可能会变得非常冗长并且有很多 if 语句。
构建一个带有一堆 if 语句的方法是CFGetTypeID()唯一的方法吗?或者有更简单的方法来做到这一点吗?
更新:举例
我想创建一个辅助函数来处理一些我无法更改的遗留代码。目前,它生成 之一CFDictionaryRef,CFStringRef或CFURLRef作为作为 a 提供的返回值CTypeRef。我目前正在通过运行CFGetTypeID()返回值来解决这个问题,但这并不理想。与其到处都有 C 风格的强制转换,我宁愿有一个CastToCF()助手来帮我处理这个问题。这也将有助于使未来的测试变得更加容易。
PS 我不担心可变类型。
这样做没有明显的意义。ac 风格的转换与其他语言不同 - 它是一种类型转换,左侧的地址与右侧的地址相同。如果您进行了错误的转换,cftypes 不会抛出或返回 null(与其他语言不同)。iow,它只是您指定类型的装饰,并且 ac 编译器将假定您的强制转换是有效的。
或者也许您可以提供一个更好的示例来说明如何使用它(如果这没有帮助)。
更新
好的。既然您将其标记为 objc++,我只需创建一个辅助类,该类具有大量诊断功能并执行所有嘈杂的转换(最小说明):
class t_helper {
public:
t_helper(CFTypeRef cf) : d_cf(cf), d_type(CFGetTypeID(cf)) { assert(this->d_cf); }
~t_helper() {}
/* type info */
bool isString() const { return CFStringGetTypeID() == this->type(); }
CFStringRef string() { assert(this->isString()); return this->cf_cast<CFStringRef>(); }
bool isDictionary() const { return CFDictionaryGetTypeID() == this->type(); }
CFDictionaryRef dictionary() { assert(this->isDictionary()); return this->cf_cast<CFDictionaryRef>(); }
...
/* and a trivial example of an operation */
void appendMutableCopyToArray(CFMutableArrayRef array) {
if (this->isString()) {
CFMutableStringRef cp(CFStringCreateMutableCopy(0,0,this->string()));
CFArrayAppendValue(array, cp);
CFRelease(cp);
}
...
}
...
private:
template < typename T > T cf_cast() { return reinterpret_cast<T>(this->d_cf); }
const CFTypeID type() const { return this->d_type; }
private:
CFTypeRef d_cf;
const CFTypeID d_type;
};
Run Code Online (Sandbox Code Playgroud)
如果没有您正在处理的程序的真正具体示例,这大约是我所能得到的最准确的结果。