Steven T. Hatton wrote:
As I was reading through some of the stuff in the Standard, I started to
wonder if there might be reason to define classes in response to runtime
conditions, say, to match some kind of new data record format. It may be
an extremely overelaborate approach to problem solving, but it may also
have arguments in its favor. Does anybody know of a system which can
accept a class definition at runtime, compile it, then instantiate the
class in the running program?
[snip]
You would need a compiler on the target system. This is not as difficult
as it sounds -- Windows XP and up have at least the visual C++ .NET 2002
(even 2003, depending on what version of .NET is installed), Linux and
other unices generally have gcc. Or you could just distribute gcc with
your app.
The reason .NET ships with a C++ (and C#, VB.NET, etc) compiler in its
framework is that it takes this precise approach. In Reflection.Emit (I
think it's called) they take a String with the code, which is then
written out to a temporary file, compiled and a pointer to an
instantiated object of that class is returned. I believe -- I'm a little
rusty on the details.
There are two basic problems here:
1) You need a compiler on the platform, or you need to distribute your
own. It must work correctly. You must be able to interface with it
adequately. It must be standard conforming to the extent that you don't
have to worry too much about errors in standard code on every single
platform.
2) You must be able to interface with the generated code. To tell the
truth this is probably the hard part.
Oh, and don't forget that C++ compilers tend to be very slow (by
comparison to C#, for example) so this technique is probably not worth
the effort in the vast majority of cases.
-- Pete