User defined types: Problems with ref
Chris
wendlec at tcd.ie
Thu Jan 23 07:47:28 PST 2014
On Thursday, 23 January 2014 at 15:34:38 UTC, FreeSlave wrote:
> On Thursday, 23 January 2014 at 15:24:19 UTC, Chris wrote:
>> Here's what I'm trying to do.
>>
>> struct Element(T) {
>> T x;
>> T y;
>>
>> public void setX(T value) {
>> x = value;
>> }
>> // More fancy functions ...
>> }
>>
>> I store Element(s) in an array and want to pass each one by
>> reference, which does not work.
>>
>>
>> class Tree {
>>
>> Element!string[] elements;
>>
>> public ref auto createElement(string name) {
>> elements ~= Element!string(name);
>> return elements[$-1];
>> }
>> }
>>
>> in main:
>>
>> auto tag = Element!string("first");
>>
>> The elements in Tree.elements and the ones in main are not the
>> same, instead I obtain a copy of each.
>> How can I make them refer to the same Elements? If I have to
>> add a .ptr property to Element, how do I do that? Is that
>> possible at all or did I shoot myself in the foot with the
>> template?
>
> You can use pointer
>
> Tree tree = new Tree();
> Element!(string)* element = &tree.createElement("first");
>
> & is to get address of returned value element.
>
> You also can rewrite your function like this:
>
> public Element!(string)* createElement(string name) {
> elements ~= Element!string(name);
> return &elements[$-1];
> }
>
> to return pointer without need to get address on caller side.
Thanks, that was fast! Yes I was tinkering around with pointers,
but didn't get it right, you did. However, the output is still
the same, i.e. two different sets:
// After creating and changing
<div id="1">
Hello, world!
<span>
</span>
</div>
// The Elements in Tree.elements:
[<div>
</div>
, <span>
</span>
]
More information about the Digitalmars-d-learn
mailing list