[Issue 9825] New: Add ability to auto-generate a specific field constructor

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Mar 28 12:48:54 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=9825

           Summary: Add ability to auto-generate a specific field
                    constructor
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: andrej.mitrovich at gmail.com


--- Comment #0 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2013-03-28 12:48:51 PDT ---
Let's say you have a Rectangle struct:

struct Rect
{
    int x;
    int y;
    int width;
    int height;
}

Later on you add two additional structures:

struct Point
{
    int x;
    int y;
}

struct Size
{
    int width;
    int height;
}

So as a convenience you want to enable constructing a Rect with these types:

struct Rect
{
    int x;
    int y;
    int width;
    int height;

    /** Construct from Point and Size. */
    this(Point point, Size size)
    {
        this.x = point.x;
        this.y = point.y;
        this.width = size.width;
        this.height = size.height;
    }
}

However this disables the default field-based constructor.

We should have the ability to explicitly reintroduce the field-based
constructor. 

But to avoid accidentally generating the field constructor for *any* field we
can take advantage of the 'default' keyword for marking which fields should be
part of a default ctor. For example:

struct S
{    
    // non-default ctor
    this(string first, string last) { this.name = first ~ last; }  
    string fullname;

default:
    int field1;
    int field2;
}

Here a default constructor would be generated that only initializes the fields
marked as 'default', in other words the above can be constructed with:

auto s1 = S("John", "Doe");  // custom ctor
auto s2 = S(1, 2);  // default ctor

The benefit here is that a default ctor is only generated for fields marked as
default, meaning that introducing new non-default fields does not update the
default ctor.

Perhaps the feature could be incorporated for classes too.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list