mardi 3 mars 2020

Proper design for C++ class wrapping multiple possible types

I am trying to implement a C++ class which will wrap a value (among other things). This value may be one of a number of types (string, memory buffer, number, vector).

The easy way to implement this would be to do something like this

class A {
    Type type;

    // Only one of these will be valid data; which one will be indicated by `type` (an enum)
    std::wstring wData{};
    long dwData{};
    MemoryBuffer lpData{};
    std::vector<std::wstring> vData{};
};

This feels inelegant and like it wastes memory.

I also tried implementing this as a union, but it came with significant development overhead (defining custom destructors/move constructors/copy constructors), and even with all of those, there were still some errors I encountered.

My last approach would be to make each member an std::optional, but this still adds some overhead.

Which approach would be the best? Or is there another design that works better than any of these?

Aucun commentaire:

Enregistrer un commentaire