Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing upcasts for C style array pointers

Tags:

c++

casting

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.

like image 250
uebe Avatar asked Sep 28 '17 12:09

uebe


1 Answers

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.

like image 81
John Zwinck Avatar answered Sep 21 '22 10:09

John Zwinck