Function name

bearophile bearophileHUGS at lycos.com
Thu Apr 22 16:48:31 PDT 2010


In Python I sometimes use the name of a given function reference (all lambdas are named "<lambda>"), this is a minimal example:


def add(a, b): return a + b
def mul(a, b): return a * b
for func in [add, mul]:
    print func.__name__, func(10, 20)


In D for object references it's easy to find the name at runtime:
object_reference.classinfo.name

But for functions the situation is less simple. 

Here are two ways I have found:


import std.stdio: writeln;
import std.typetuple: TypeTuple;
import std.typecons: tuple;

int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }

void main() {
    // solution 1
    foreach (name; TypeTuple!("add", "mul"))
        mixin(`writeln(name, " ", ` ~ name ~ `(10, 20));`);

    // solution 2
    auto funcs = [tuple("add",&add), tuple("mul",&mul)];
    foreach (ptr_name; funcs)
        writeln(ptr_name.field[0], " ", ptr_name.field[1](10, 20));

    // hypothetical solution 3
    auto funcs_ptr = [&add, &mul];
    foreach (func; funcs_ptr)
        writeln(func.name, " ", func(10, 20));
}


The first solution is not good because it uses a static foreach and I like to avoid messy string mixins when possible.

The second solution is better, and I can use it, but it requires redundancy in those names that can cause bugs.

The third solution is what I'd like to be able to write. To have such run-time reflection the compiler has to store in the binary a dictionary that maps function pointers and delegates to their names as strings (lambdas can be mapped to standard name). This can inflate the binary a little. This is not too much different from the data classes have, like their name that can be found with classinfo. What do you think?

Bye,
bearophile



More information about the Digitalmars-d mailing list