lundi 26 octobre 2020

Dynamic class type from file data

I have some JSON files in which I define objects of various types. The types are given as a field within the objects. I want to load the file and for each JSON object, create a new class of that type and pass the rest of the JSON data to its constructor.

The issue is that I'd rather not have a huge case statement matching the type and creating an object of that type. Here are some of the possibilities I've considered:

  1. Reflection. I don't know too much about it, but my understanding is that it might allow me to create a class in this manner. While I'm aware C++ doesn't provide this capability natively, I've seen a few libraries such as this one that might provide such functionality.

  2. Create an enum of class types. Create a template function that takes a type parameter from this enum and creates an object of that type. Use something like smart_enum to convert the string field.

Option 2 seems like a good one but I haven't been able to get this working. I've done extensive googling, but no luck. Does anyone know how I might go about doing this, or if there is a better option which I have not considered? Apologies if this has been answered elsewhere, perhaps under a term which I do not know; I have spent quite a lot of time trying to solve this problem and had no luck.

Please let me know if I can provide any additional information, and thank you.

Edit: here's an example of what I've tried to get option 2 working.

#include <iostream>
#include <string>

enum class Animals {
    Dog,
    Cat
};

class Dog {
public:
    std::string sound{"woof"};
};

class Cat {
public:
    std::string sound{"meow"};
};

template<Animals animal> void make_sound() {
    new animal();
    cout << animal.sound << endl;
}

int main() {
    make_sound<Animals::Dog>();
    make_sound<Animals::Cat>();

    std::exit(1);
}




Aucun commentaire:

Enregistrer un commentaire