Getting the parameters of a struct/class constructor

Andrej Mitrovic andrej.mitrovich at gmail.com
Thu Jan 24 14:49:23 PST 2013


On 1/24/13, Philippe Sigaud <philippe.sigaud at gmail.com> wrote:
> IIRC, you can use __traits(getOverloads, mytype.__ctor) to get all
> constructor overloads.
> See:
> http://dlang.org/traits.html#getOverloads
>
> I used this in conjunction with __traits(getMember, ...) to get the
> entire list of member, overloads included.
>

I don't understand why, but it seems DForum doesn't show up any of my
posts. I've posted this as my second reply (hope this makes it):

If you have multiple constructors you can pick the parameters with a
helper template:

import std.traits, std.string;

struct A
{
        this(int a, double b)
        {
        }

    this(float y)
    {
    }
}

template PickCtorParams(Type, size_t index)
{
    enum ctorLen = __traits(getOverloads, Type, "__ctor").length;
    static if (index < ctorLen)
    {
        alias ParameterTypeTuple!(__traits(getOverloads, A,
"__ctor")[index]) PickCtorParams;
    }
    else
    {
        static assert(0,
            format("index %s exceeds %s ctors for type %s", index,
ctorLen, Type.stringof));
    }
}

void main()
{
    pragma(msg, PickCtorParams!(A, 0));  // (int, double)
    pragma(msg, PickCtorParams!(A, 1));  // (float)
    pragma(msg, PickCtorParams!(A, 2));  // out of bounds
}


More information about the Digitalmars-d-learn mailing list