Feature request - simpler constructors

Bill Baxter dnewsgroup at billbaxter.com
Thu Sep 20 06:55:17 PDT 2007


Janice Caron wrote:
> Please could we let
> 
>  this(auto n) {}
>  T n;
> 
> be syntactic sugar for
> 
>  this(T n)
>  {
>      this.n = n;
>  }
>  T n;
> 
> I've lost count of the number of times I've written constructors which
> do nothing but copy function parameters into member variables. If you
> have a lot of variables, it gets very tedious, especially when you
> have to do it over and over again. I tend to give my constructor
> paramters different names to avoid typing "this." all the time, but I
> still end up with, for example:
> 
>  class MyDate
>  {
>      this(int year_, int month_, int day_, int hour_, int minute_, int second_)
>      {
>          year = year_;
>          month = month_;
>          day = day_;
>          hour = hour_;
>          minute = minute_;
>          second = second_;
>      }
> 
>      int year;
>      int month;
>      int day;
>      int hour;
>      int minute;
>      int second;
>  }
> 
> Just think how much nicer it would be if instead I could just type
> 
>  class MyDate
>  {
>      this(auto year, auto month, auto day, auto hour, auto minute, auto second)
>      {
>      }
> 
>      int year;
>      int month;
>      int day;
>      int hour;
>      int minute;
>      int second;
>  }
> 
> That would be /so cool/. "auto" can have no other possible meaning in
> this context. Plus, it would make writing constructors just a little
> bit safer, because if the constructor calls some other function which
> relies on the variable having been initialised, it will have been, and
> if the constructor calls some non-member function, we'll be able to
> call it as f(year) instead of f(year_) with no fear of year being
> uninitialised.


I like the idea but I'm not wild about the syntax you've chosen.  I'd 
like to be able to read off the types of the parameters from the 
function signature without having to dig around in the class for where 
the memebers are defined.  What about something like prefixing the name 
with a dot?


    this(int .year, int .month, int .day, int .hour, int .minute, int 
.second)

The thing I've always wished were possible with parameter lists was to 
omit types that are repeated like in other variable declarations.  So 
you could have:

    foo(int year, month, day, hour, minute, second) { ... }

It might be less error-prone to combine this with  ; to terminate a list 
(also like in normal declarations):

    foo(int year, month, day, hour, minute, second; float fraction) { ... }

ANSI C parameter declarations were in some was a step back from K&R 
where you could do:

    foo(year, month, day, hour, minute, second, fraction)
       int year,month,day,hour,minute;
       float fraction;
    { ... }

Er .. nevermind.  On second thought, K&R sucked.

--bb



More information about the Digitalmars-d mailing list