Answer the question
In order to leave comments, you need to log in
Is it possible to create an object at runtime in C++?
Help people.
I kind of know what introspection is, using C# and Python as an example. In the latter, a complex object is dynamically created in my project at runtime. Is it possible to create an object in C++ at runtime (and access it in advance from the code)?
For example, something like this:
auto object = ObjectFactory::genererateObject(objectToParse);
object.field1.field2 = NULL;
In the spirit of this?
Answer the question
In order to leave comments, you need to log in
The question is a little unclear. But as you wrote, yes, you can. During compilation, the compiler will determine the type that your class returns and substitute it for "auto". If you access invalid fields that are not native to that type, the compiler will tell you this at compile time.
But still the example you gave is not introspection. Introspection in C++ is achieved through RTTI. In your example, the type of the object is known at compile time.
you can try something like this:
typedef boost::variant<int, string, bool> field_t;
typedef std::map<string, field> settings_t;
struct A
{
A(file)
: settings_(file.parse())
{}
private:
settings_t settings_;
int my_method()
{
int a = boost::get<int>(settings_["a"]);
int b = boost::get<int>(settings_["b"]);
return a + b;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question