简体   繁体   中英

C++ how can I define classes at runtime?

The idea is to create object at runtime in C++.

The input for this creation is going to be a json file. For example

{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}

What are the options to do this in C++? Can boost help on this?

You can't do (define classes at runtime) that in standard C++, because a class has some code associated to it (at least, implicit constructors and destructors, and very often member functions, and very often has some vtable , generated by the compiler, pointing to code).

Your JSON parsing library (eg jsoncpp ) will provide a type representing arbitrary JSON objects (in braces).

On some operating systems , you could load a plugin (containing code) at runtime; on Linux and POSIX use dlopen(3) but beware of name mangling (see C++ dlopen Mini-HowTo ). The plugin is a shared object that you need to compile specifically as position-independent code . Several framework libraries ( Qt , POCO , Boost DLL ...) provide common abstractions to load plugins, ...

You could even (I did that in MELT , on Linux) generate some C++ code on the fly at runtime in some temporary file, compile that temporary file into some temporary plugin, and load that plugin .... all this in the same process .

You could do this, or something close to this (i'm simplifying):

class VariableClass
{
private:
   typedef map<string, boost::any> MembersMap;

   string objectType;  // a label, defined at parsing... 
                       // could be an ID, but then you'd already know 
                       // the members to expect, and could use a 'regular' class.
   MembersMap members;

... etc...
   boost::any& operator [](const std:string& s) ( return members[s]; }
};

This is oversimplified, but should do what you want. You may want to replace boost::any with std::variant, or a custom specialized template class holding the types you want, which could also be determined at runtime from the json.

[edit] I've added a variable 'objectType'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM