Using traits how do i get a function's parameters as a string?

Andrej Mitrovic andrej.mitrovich at gmail.com
Tue Sep 3 14:19:53 PDT 2013


On 9/3/13, Gary Willoughby <dev at nomad.so> wrote:
> Using traits how do i get a methods's parameters as a string? Say
> i have the following method:

Here's a first attempt:

-----
import std.range;
import std.string;
import std.stdio;
import std.traits;

class C
{
    void setAge(int age, int)
    {
    }
}

template GetParamsString(alias func)
{
    string getParamsString()
    {
        string[] paramTypes;
        string[] paramNames;

        foreach (id; ParameterTypeTuple!func)
            paramTypes ~= id.stringof;

        foreach (id; ParameterIdentifierTuple!func)
            paramNames ~= id;

        string[] result;

        foreach (type, name; zip(paramTypes, paramNames))
            result ~= format("%s %s", type, name);

        return format("(%s)", result.join(", "));
    }

    enum GetParamsString = getParamsString();
}

void main()
{
    string x = GetParamsString!(C.setAge);
    writeln(x);
}
-----

Others will find a few ways to simplify this, I'm sure. :)


More information about the Digitalmars-d-learn mailing list