c++ - const_cast to "void pointer" from "const T pointer" fails -
why following code fails compile?
cfdictionaryref dictionary; cfdictionaryapplyfunction(dict, set, const_cast< void * >(dictionary));
error: const_cast 'cfdictionaryref' (aka 'const __cfdictionary *') 'void *' not allowed cfdictionaryapplyfunction(scoped, setdictionary, const_cast<void *>(dictionary)); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if set c-style type cast void * works fine
cfdictionaryapplyfunction(dict, set, ( void * )dictionary);
do reinterpret_cast<void *>(const_cast< __cfdictionary * >(dictionary))
const_cast designed cast between const pointers or references , non-const equivalents. convert different type (void* in case), need use reinterpret_cast. reinterpret_cast "reinterprets" same sequence of bits different type. however, not allowed cast away constness, need use both casts together.
edit: @ant points out, since target void *, can use static_cast instead of reinterpret_cast. in fact, considered safer, because standard guarantees same address result. reinterpret_cast, on other hand, guarantees original value obtained reinterpret_cast ing result of first cast back. however, applies restricted set of conversions (void *, base-derived class pairs). reinterpret_cast more general, although relying on compiler reasonable thing.
Comments
Post a Comment