Call function by its string name
John Colvin
john.loughran.colvin at gmail.com
Sat Oct 19 10:35:51 PDT 2013
On Saturday, 19 October 2013 at 17:17:47 UTC, aldanor wrote:
> On Saturday, 19 October 2013 at 16:56:50 UTC, John Colvin wrote:
>> On Saturday, 19 October 2013 at 16:33:11 UTC, aldanor wrote:
>>> I was wondering if it was possible to call D functions by
>>> their names (strings that are not known at compile time) and
>>> couldn't find the answer anywhere in the documentation. Kinda
>>> like we can instantiate objects with Object.factory, would it
>>> be possible to somehow do the same with module-level
>>> functions? Or maybe with non-static class methods?
>>
>> You could make an associative array of function pointers with
>> strings as keys. Probably not the best solution but it should
>> work.
>
> Thanks for the reply, this is something I thought about of
> course. But what if I have hundreds of functions to dispatch
> to? The current (C) implementation does exactly that,
> autogenerates a sort of an associative array, but that's very
> ugly and requires an extra preprocessing step.
>
> I was thinking runtime reflections can help do this, but I'm
> not quite sure where to start (and there is also the
> performance question).
No matter what happens, if you want to take a runtime string and
work out what function it corresponds to then you're going to
have to use some sort of string matching.
Unless you have a very specific function name format then a hash
is probably the fastest way to do this, especially in the case of
hundreds of functions.
D's compile-time reflection could probably make building the
associative array neat and easy.
More information about the Digitalmars-d
mailing list