Is there a way to initialize a non-assigned structure declaration (or is it a definition)?

Ali Çehreli acehreli at yahoo.com
Fri Nov 9 15:57:35 PST 2012


On 11/09/2012 03:35 PM, Too Embarrassed To Say wrote:
 > struct Parameterized(T, U, V, W)
 > {
 > T t;
 > U u;
 > V v;
 > W w;
 > this(T t, U u, V v, W w)
 > {
 > this.t = t;
 > this.u = u;
 > this.v = v;
 > this.w = w;
 > }
 > }

You are obviously using this just as an example but I wanted say that 
you don't need a constructor because structs provide an automatic one 
that copies the arguments to the members one by one.

 > Parameterized!(int, double, bool, char) p1; // compiles
 > // or
 > auto p2 = Parameterized!(int, double, bool, char)(); // must have the
 > empty () to compile
 > // or
 > auto p3 = Parameterized!(int, double, bool, char)(57, 7.303, false,
 > 'Z'); // compiles

That is my preference.

 > // but not
 > // Parameterized!(int, double, bool, char)(93, 5.694, true, 'K') p4;
 > // Error: found 'p4' when expecting ';' following statement
 > // nor

I don't expect that to work; the arguments must go after the variable there.

 > // Parameterized!(int, double, bool, char) p5(93, 5.694, true, 'K');
 > // Error: found 'p5' when expecting ';' following statement

Ok, that is strange. I don't understand what "statement" the compiler 
sees there.

 > // nor, OK this was a crazy try
 > // Parameterized!(int 93, double 5.694, bool true, char 'K') p6;
 > // Error: found '93' when expecting '.' following int

No, that shouldn't work.

There is also the common idiom of providing a convenience function to 
help with template parameter deduction:

auto parameterized(T, U, V, W)(T t, U u, V v, W w)
{
     return Parameterized!(T, U, V, W)(t, u, v, w);
}

/* ... */

     auto p7 = parameterized(93, 5.5, true, 'K');

Ali



More information about the Digitalmars-d-learn mailing list