Search code examples
c++arraysc++17variantvariable-length-array

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;

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.