navderm navderm - 4 months ago 18
C++ Question

error converting a const void* to some other pointer without const_cast

The function

int compare(const void* a, const void* b)
{
SomeDataType g1 = *(static_cast<SomeDataType*>(a));
SomeDataType g2 = *(static_cast<SomeDataType*>(b));
g1.firstelement < g2.firstelement ? 1 : -1;
}


This code returns an error saying "static cast can't cast from const void* to SomeDataType*." I use const_cast like

SomeDataType g1 = *(static_cast<SomeDataType*>(const_cast<void*>(a))) ;


to get this working. Is that a right way to do it ? Or am I missing something? I am not understanding quite how this works.

Answer

It doesn't feel right because it shouldn't feel right. Someone gave you a pointer and in the interface you promised that you would not modify it, casting away the const is breaking your promise (well, not really, but the type system considers that if you cast away const, is is because you want to modify the object, which would break your promise).

I suggest that you don't drop the const:

int compare(const void* a, const void* b)
{
    SomeDataType g1 = *(static_cast<const SomeDataType*>(a));
    SomeDataType g2 = *(static_cast<const SomeDataType*>(b));
    return g1.firstelement < g2.firstelement ? 1 : -1;
}