How to chain constructor args to a template memeber

Philippe Sigaud philippe.sigaud at gmail.com
Thu Mar 11 12:33:07 PST 2010


On Thu, Mar 11, 2010 at 21:03, BCS <none at anon.com> wrote:

>
>
>> i.e.
>>
>> static C create(Args...)(int foo, float bar, Args args)
>> {
>> auto c = new C(foo, bar);
>> c.t = T(args);
>> return c;
>> }
>>
>
> What about a static function instead of a constructor?
>

Two variations on the same theme:

storing (Args...) as a template parameter in the host class

class Host(Hosted, Args...) {
    Hosted t;
    this(int foo, float bar, Args args)
    {
     t = Hosted(args);
    }
}

and using a helper function to do the type extraction:

Host!(Hosted, Args) host(Hosted, Args...)(int foo, float bar, Args args)
{
    return new Host!(Hosted, Args)(foo, bar, args);
}

Or, give the host a constructor taking a Hosted already created:


class Host2(Hosted) {
    Hosted h;
    this(int foo, float bar, Hosted h)
    {
        this.h = h;
    }
}

Host2!(Hosted) host2(Hosted, Args...)(int foo, float bar, Args args)
{
    auto h = Hosted(args);
    return new Host2!(Hosted)(foo, bar, h);
}

Usage:

struct OneArg { char c;}

struct ManyArgs { int i; float f;}

void main()
{
    auto c0 = host!ManyArgs(1,2.0,3,4.0);
    auto c1 = host!OneArg(1,2.0,'c');
    auto c2 = host2!ManyArgs(1,2.0,3,4.0);
 }
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100311/aa01f3a9/attachment.htm>


More information about the Digitalmars-d-learn mailing list