www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Feature request: Make object composition easier

reply "TommiT" <tommitissari hotmail.com> writes:
Given the following:

struct Foo
{
     int val;
     ref Foo opUnary(string op : "++")()
     {
         ++val;
         return this;
     }
}

struct Bar
{
     Foo _foo;
     alias _foo this;

     void fun() { }
}

Bar bar;

... I would like to be able to say:

(++bar).fun();

... which would be lowered to:

(*cast(Bar*) ((cast(byte*) &++bar) + 
Bar.init._foo.offsetof)).fun();

... except that it would be considered  safe.

The logic is that certain operators, like pre-increment and 
assignment operators and such, can be assumed to be return a 
reference to the operand variable (given that the operator 
returns a ref to that type). Let's call this particular set of 
operators X. The rule would then be: If a call to an operator is 
re-routed through alias-this to a field of the operand, and the 
operator is in X, and the operator returns a ref to the type of 
the field, then the return value is implicitly converted to a ref 
to the operand.
Mar 25 2013
next sibling parent "TommiT" <tommitissari hotmail.com> writes:
Or, do you think mixin templates would be better suited for code 
re-use, than object composition?
Mar 25 2013
prev sibling next sibling parent "TommiT" <tommitissari hotmail.com> writes:
On Monday, 25 March 2013 at 18:15:21 UTC, TommiT wrote:
 (++bar).fun();

 ... which would be lowered to:

 (*cast(Bar*) ((cast(byte*) &++bar) + 
 Bar.init._foo.offsetof)).fun();
Sorry, meant to say: (*cast(Bar*) ((cast(byte*) &++bar) - Bar.init._foo.offsetof)).fun();
Mar 25 2013
prev sibling parent "TommiT" <tommitissari hotmail.com> writes:
On Monday, 25 March 2013 at 18:15:21 UTC, TommiT wrote:
 ... I would like to be able to say:

 (++bar).fun();
Actually, let's forget about this proposal. I thought about it a bit more, and I'm convinced that object composition is not the correct tool for what I'm trying to achieve. The mere fact, that post-increment operator in Foo cannot be composed into Bar like pre-increment could in the example above, is a clear indication that the tool isn't right for the job.
Mar 26 2013