Template type deduced from struct ctor?

monarch_dodra monarchdodra at gmail.com
Thu Mar 27 10:57:15 PDT 2014


On Thursday, 27 March 2014 at 17:42:24 UTC, Luís Marques wrote:
> Could this be made to work?
>
>     struct S(T)
>     {
>         T x;
>
>         this(T x)
>         {
>             this.x = x;
>         }
>     }
>
>     void main()
>     {
>         int x = 42;
>         auto s = S(x); // fails to deduce T
>     }

This is usually done via a "constructor function", that's the 
name of your struct, but with a lower case start letter. EG:

//----
     /// Some struct parameterized on T.
     struct MyStruct(T)
     {
         T x;
         this(T x)
         {
             this.x = x;
         }
     }

     /// convenience to build a MyStruct
     auto myStruct(T)(T t)
     {
          return MyStruct!T(t);
     }

     void main()
     {
         int x = 42;
         auto s = myStruct(x); // succeeds in deducing T
     }
//----

This "old standing" trick predates D, and comes from C++, with 
functions such as
//----
namespace std
{
     pair<T1, T2> make_pair<T1, T2>(T1 t1, T2 t2)
     {
         return pair<T1, T2>(t1, t2);
     }
}
//----


More information about the Digitalmars-d mailing list