www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - converting a string function name to an actual function call

reply oliver <oliver.ruebenkoenig web.de.REMOVE> writes:
Hi everyone,

is it possible to program kind of a general function that applies the name of a
function (given as a char [] ) to arguments. The following code does not work
but something in the same spirit.

Thanks once more to this very patient group.
Oliver

-------

import std.stdio;

int f1( int a ) { 
    return a+1;
}

int f2( int b ) { 
    return b-10;
}

int apply(char [] name, int arg) {
    return name(arg);
}

int main() {
    int i = 1;
    i = f1(i);
    writefln("i: ",i);
    i = f2(i);
    writefln("i: ",i);
    i = apply( "f1", i );
    i = apply( "f2", i );
    writefln("i: ",i);
    return 0;
}
Nov 27 2007
parent Bill Baxter <dnewsgroup billbaxter.com> writes:
oliver wrote:
 Hi everyone,
 
 is it possible to program kind of a general function that applies the name of
a function (given as a char [] ) to arguments. The following code does not work
but something in the same spirit.
 
 Thanks once more to this very patient group.
 Oliver
 
 -------
 
 import std.stdio;
 
 int f1( int a ) { 
     return a+1;
 }
 
 int f2( int b ) { 
     return b-10;
 }
 
 int apply(char [] name, int arg) {
     return name(arg);
 }
 
 int main() {
     int i = 1;
     i = f1(i);
     writefln("i: ",i);
     i = f2(i);
     writefln("i: ",i);
     i = apply( "f1", i );
     i = apply( "f2", i );
     writefln("i: ",i);
     return 0;
 }
 
For compile-time strings that's what the string mixin does: int apply(char[] name)(int arg) { mixin("return " ~ name ~ "(arg);") } int i=1; i = apply!("f1")(i); For runtime string -- no dice. You'll need to make a map of strings to function pointers or a big switch statement. Maybe DDL gives you a way to emulate this via functions in DLLs but it's not a feature of the language itself. --bb
Nov 27 2007