Search code examples
c++wt

Keeping Class Info In Database


I have several classes (same base class) and only some users allowed to instantiate some. I need to keep allowed classes for a user in a database.

I definitely need some suggestions. Because I think, I should not need to have a list of class names as a string in database and instantiate them in a condition of string comparison. It just does not feel right to me.

Typical scenario is
1. Calling GetAllowedClassesToInstantiate(user) [From Database]
2. Instantiate those classes

Do you have any suggestions?

Regards, Burak


Solution

  • Make a data structure like this:

    class BaseClass;
    
    std::map<std::string, std::function<BaseClass*()> Factories;
    

    and initialize it in the following way:

    class One : BaseClass { ... }
    
    void init() {
        Factories["One"] = [](){ return new One(); }
    }
    

    Basically it will serve as a lookup ClassName -> Constructor.

    Keep allowed class names in the database. After you retrieve it, present it to the user and when he chooses an option, look up the proper constructor wrapper function in Factories and use it to instantiate the selected class.

    Make sure to keep the database entries up-to-date with the entry keys inFactories.

    (I've used some C++11 in the code sample. You can do the same in C++03 with a bit more code, without the lambda expression and std::function, but the idea stays the same.)