How do I create classes dynamically?
Ali Çehreli
acehreli at yahoo.com
Thu Apr 15 23:32:13 UTC 2021
On 4/15/21 1:56 PM, mw wrote:
>>> I wanted to find out if it is possible to create classes dynamically.
>>
>> out of curiosity: Why you would like to do this? I cannot think of a
>> use case for this - this is why i ask.
>
> In response to user input?
That's a different question because creating a class is different from
creating instances (objects) of existing classes.
> again, one can manually dispatch, but is there a way to avoid this
> tediousness?
H. S. Teoh showed methods where lookup keys are known at compile time
and are used to generate e.g. a switch statement.
I have a system where the main logic of the program has no idea what
types are out there. All it has is a lookup table. (Uncompiled pseude
code follows.)
struct Functions {
void * function deserialize(ubyte[] bytes);
void function process(void* input, void* output);
void function serialize(ubyte[] bytes);
}
shared Functions[string] registration;
So, the main logic uses user input to look up what the functions are:
auto funcs = registration[userInput];
And applies those functions to some data at runtime.
This is "dynamic" because registration is populated by the 'shared
static this()' blocks of unknown modules that are loaded dynamically
(and in my case conditionally):
module foo;
// This struct is what this module is about:
struct Foo {
// ...
}
// The module registers itself with the main lookup system when loaded:
shared static this() {
register("my lookup string",
Functions(&deserializer!Foo,
&processor!Foo,
&serializer!Foo));
}
Note that registered functions are template instances tailored for this
specific type. However, the main logic has no klowledge of individual
modules, not even the templates like 'deserializer': It only knows about
a lookup table that contains some function pointers.
I haven't used object creation functions above but that can be added to
Functions as well.
Ali
More information about the Digitalmars-d-learn
mailing list