Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

struct with variable length array in std::variant

So I’m working with this struct type with variable length array member, like this:

struct Entry;

struct Data {
    int members;
    size_t entries_size;
    Entry entries[1];
};

The entries_size member is the actual size of the entires array, it is only known when read from network. The problem is that I’d like to use it in a std::variant among other network data types, how can I put it into a std::variant with the footprint of the whole data object, without dangling pointers flying around?

std::variant<Data, OtherData2, OhterData3...> v;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As has been pointed out, this is not legal C++. It just wont work this way. However, if the amount of entries is bound, it might be possible to do this:

template <std::size_t N>
struct Data {
    int members;
    static constexpr std::size_t entries_size = N;
    Entry entries[N];
}; // Of couse, you might want to use std::array<Entry,N> instead!

// ...
std::variant<Data<2>, Data<8>, Data<32>> example;

This, of course, is highly situational. If you know the incoming data will fall into either 2, 8 or 32 entries, you can specify these at compile time. If the amount of entries is completely variable, with no guarantees, use std::vector. That’s what it’s for.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading