Search code examples
c++structgeneric-type-argument

create "generic" structures in c++


I want to create a structure within a structure that is defined at runtime, with variables that I can reference in the parent structure's functions. Basically, this:

struct Bar
{
  int val = 0;
}
struct Foo
{
  struct *generic_struct;
  Foo()
  {
    generic_struct = Bar;
    generic_struct.val++;
  }
}
int main()
{
  Foo foo;
}

I know that that's not what pointers do, but I don't have a better way to describe what I expect. I also from my limited understanding of C++ realize that there is probably no way to do what I want, but what would be the best closest thing?


Solution

  • Quite a few options:

    I. Use inheritance.

    struct Struct {
        virtual Struct &setVal(int) = 0;
        virtual ~Struct() {}
    };
    struct Bar: Struct {
        int val = 0;
        Struct &setVal(int that) { val = that; return *this; }х
    };
    struct Foo {
        std::unique_ptr<Struct> str;
        Foo(): str(std::make_unique<Bar>()) {}
    };
    

    II. (Somewhat Pythonic/javascripty.) Use maps. This way they are really runtime provided you know the set of all the possible types struct's fields can belong to.

    template<typename... types> using Struct
         = std::unordered_map<std::string, std::variant<types...>>;
    auto bar() { return Struct<int, char, double>{{"val", 0}}; }
    
    struct Foo {
         Struct<int, char, double> generic_struct;
         Foo(): generic_struct(bar()) {
             ++std::get<int>(generic_struct["val"]);
         }
    };
    

    III. Make Foo templated, if you can.

    template<typename Struct> struct Foo {
         Struct generic_struct;
         Foo() { ++generic_struct.val; }
    };
    

    (Add some SFINAE to make all the struct accesses compile.)

    Others are probably even more complicated.