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.
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;
}
Do this:
const SomeDataType g1 = *static_cast<const SomeDataType *> (a);
const SomeDataType g2 = *static_cast<const SomeDataType *> (b);
You don't need const_cast here.
However I prefer this:
int compare(const SomeDataType &g1, const SomeDataType &g2)
{
return g1.firstelement < g2.firstelement ? 1 : -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With