struct Entry
{
int Data0;
};
struct ExtendedEntry : public Entry
{
int Data1;
};
I have a simple method expecting a C-style array pointer to Entry like this
void Calculate(Entry* data, int count);
This method obviously fails, when passing a pointer to an array of ExtendedEntrys. How to prevent users from doing so?
ExtendedEntry items[50];
// [...]
Calculate(items, 50);
It's not that I pursue a bullet-proof API, I just want to prevent me and my co-workers from making the same mistake again.
Make a simple wrapper:
template <typename TEntry>
void CalculateSafe(TEntry* data, int count)
{
static_assert(sizeof(TEntry) == sizeof(Entry), "size mismatch");
Calculate(data, count);
}
This enables passing any derived type so long as it has the same size, which will solve the problem you're having when a C API needs to do pointer arithmetic in an array.
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