Is there a way in C++ to "compare" a string with a typename?

Viewed 140

I have a json with initial values and a manager that creates objects. The values are read as string but the manager needs the typename to create the object.

I have something like this

for(auto obj_str : json["objs"])
{
    if(obj_str == "ObjectFoo")
    {
        manager.createObject<ObjectFoo>();
    }
    if(obj_str == "ObjectBar")
    {
        manager.createObject<ObjectBar>();
    }
    if(obj_str == "ObjectBaz")
    {
        manager.createObject<ObjectBaz>();
    }
}

Is there a way to avoid using an if statement per object with one or more generic functions? The string of the object is always the same as the typename.

1 Answers

Although there may be some other way of doing that which does not involve an if statements, there will have to be somewhere, in some form or fashion, some code that translates between strings and discrete types.

This is fundamental to C++: the types of all objects and expressions must be known, and determined, at compile time. This is hard, immutable rule, and there are no exceptions, and you are running into this fundamental, core C++ principle.

Instead of an if statement, other possibilities include an associative container that maps a class name to a closure that instantiates an object of the given type, or receives whatever this manager object is, as a parameter, and calls the manager's template method using the associated class name.

Or there could be something completely external to C++, a script of some kind that reads a configuration file, in some structured format, and spews out robo-generated C++ code that consists of the above if statements, then integrated into your development build system, so that it gets built and rebuilt automatically, when needed.

But the short answer to your question is: unfortunately no, C++ just doesn't work this way. The value of obj_str is not known until run time. The type that any C++ expression or statement uses must be known at compile time, that's it. There is no way to reconcile this fundamental disconnect. In some form, or fashion, you will need to implement the code and logic that will check and validate obj_str for each possible value and instantiate the appropriate type, accordingly.

Related