www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Template struct literals should infer template parameters

reply Sean Eskapp <eatingstaples gmail.com> writes:
If I have something like

    struct S(T)
    {
        T data;
    }


I can't make a struct literal with

    int mystuff;
    someFunc(S(mystuff));

I have to use

    int mystuff;
    someFunc(S!(int)(mystuff));

Why is this?
Aug 06 2011
next sibling parent Philippe Sigaud <philippe.sigaud gmail.com> writes:
On Sat, Aug 6, 2011 at 22:19, Sean Eskapp <eatingstaples gmail.com> wrote:
 If I have something like

 =C2=A0 =C2=A0struct S(T)
 =C2=A0 =C2=A0{
 =C2=A0 =C2=A0 =C2=A0 =C2=A0T data;
 =C2=A0 =C2=A0}

   I can't make a struct literal with

 =C2=A0 =C2=A0int mystuff;
 =C2=A0 =C2=A0someFunc(S(mystuff));

 I have to use

 =C2=A0 =C2=A0int mystuff;
 =C2=A0 =C2=A0someFunc(S!(int)(mystuff));

 Why is this?
Yeah, function templates have a way to automatically determine their template parameters (IFTI : Implicit Function Template Instantiation?), but that doesn't work with struct and class constructors. Too bad. You can use a factory function to do just that, it's a one-liner: auto s(T)(T t) { return S!(T)(t); } and then: someFunc(s(mystuff));
Aug 07 2011
prev sibling parent Ali =?iso-8859-1?q?=C7ehreli?= <acehreli yahoo.com> writes:
On Sat, 06 Aug 2011 20:19:06 +0000, Sean Eskapp wrote:

 If I have something like
 
     struct S(T)
     {
         T data;
     }
 
 
 I can't make a struct literal with
 
     int mystuff;
     someFunc(S(mystuff));
It has been the same in C++. The reason is that the syntax above would conflict with and is reserved for a templated constructor.
 I have to use
 
     int mystuff;
     someFunc(S!(int)(mystuff));
 
 Why is this?
To allow flexibility by not tieing the struct's template parameters to its constructor's template parameters. Deduction actually works for the constructor: struct S(T) { T data; this(U)(U) {} } void someFunc(T)(T) {} void main() { double d; someFunc(S!int(d)); } The constructor's template parameter is being deduced as 'double' on the last line. Ali
Aug 07 2011