Search code examples
c++cd

Variable function calls in D


OK, so that's what I need :

  • Let's say we've got a string variable, e.g. func with some value, given by the user (not a constant)
  • How could we call a function which name is the value of func?

UPDATE:

Perhaps thought that what I needed was pretty self-explanatory, but since I'm noticing many downvotes, here you are :

string func = "myfunc";

I need something like call(func), which will call myfunc. Like PHP's call_user_func_array()


Any ideas?

I had a look at mixins but this doesn't look like what I'd need.


P.S. I'm tagging the question with c and c++ too, since a universal solution could be theoretically possible, given the similarities among the languages.


Solution

  • Programming languages generally do not provide a way to access function names during runtime, as those names are usually stripped out by the linker, leaving behind only machine code.

    As user3286380 suggested, one way to tackle this problem, which would work in all languages, is to make a table which cross-references function names and pointers to the respective functions. Then, your program can look up this table during run time.

    If the language in question allows introspection (either run-time or compile-time), you can enumerate the functions in your module or program, and find the function whose name the user entered. In D, you can do this by using the allMembers trait on a module. This will give you an array of all declarations in the module; the next step would be to filter out functions, check that the function signature matches, then generate a switch statement which calls the respective function. You can use CTFE and string mixins to achieve the above.