从"const T pointer" "void pointer" const_cast失败
const_cast to "void pointer" from "const T pointer" fails
为什么下面的代码无法编译?
CFDictionaryRef dictionary;
CFDictionaryApplyFunction(dict, set, const_cast
error: const_cast from 'CFDictionaryRef' (aka 'const __CFDictionary *') to 'void *' is not allowed
CFDictionaryApplyFunction(scoped, setDictionary, const_cast<void *>(dictionary));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
如果我将c风格的类型强制转换设置为void *,它可以正常工作
Do reinterpret_cast<void *>(const_cast< __CFDictionary * >(dictionary))
const_cast
仅用于在const
指针或引用与它们的非const
对等物之间进行强制转换。要转换为不同的类型(在您的例子中是void*
),您需要使用reinterpret_cast
。reinterpret_cast
基本上是将相同的比特序列"重新解释"为不同的类型。但是,不允许抛弃constness,因此需要同时使用两种强制转换。
编辑:正如@AnT指出的那样,由于目标是void *
,您可以使用static_cast
而不是reinterpret_cast
。事实上,它被认为是更安全的,因为标准保证您得到相同的地址作为结果。另一方面,reinterpret_cast
只保证通过reinterpret_cast
对第一次强制转换的结果获得原始值。然而,这只适用于一组有限的转换(void *
,基派生类对)。reinterpret_cast
更通用,尽管您依靠编译器来做合理的事情。