www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - ref fields of .tupleof

reply "Sharp" <sharp1113 hotmail.com> writes:
Hi all!

I've spend several hours to solve my problem, and I did it!

But don't know why it is worked in this way:
I'd like to modify all fields of an object by a specific values 
(for deserialization).

public ref T foo(T)() {
	T *ret = new T;
	// DON'T WORK
	// Looping through fields in this way doesn't modify the object
	auto fields = ret.tupleof;
	foreach(ref field; fields) {
		field = 1; // this doesn't alter 'ret'
	}

	// WORK
	foreach(ref field; ret.tupleof) {
		field = 1; // this does alter it!!!
	}
	return *ret;
}

(Of course the real code doesn't use the value '1'. It uses 
values from an ubyte[] with the corresponding types of T's fields)

Can somebody explain me why it is work like that?
Thanks a lot.
May 29 2012
next sibling parent Philippe Sigaud <philippe.sigaud gmail.com> writes:
On Tue, May 29, 2012 at 9:18 PM, Sharp <sharp1113 hotmail.com> wrote:

What does it give if you do:

 =C2=A0 =C2=A0 =C2=A0 =C2=A0foreach(index, unused; fields) {
 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0fields[index] =3D =
1;
        }
?
May 29 2012
prev sibling next sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 05/29/2012 12:18 PM, Sharp wrote:

 public ref T foo(T)() {
 T *ret = new T;
 // DON'T WORK
 // Looping through fields in this way doesn't modify the object
 auto fields = ret.tupleof;
Looks like fields is a local copy of ret.tupleof so the following modifies just that copy.
 foreach(ref field; fields) {
 field = 1; // this doesn't alter 'ret'
 }
Ali
May 29 2012
parent "Sharp" <sharp1113 hotmail.com> writes:
Thanks a lot Ali, I understand now!

Philippe, based on what Ali said, your code will give exactly the 
same result because it looping through a local copy of 
ret.tupleof.
May 29 2012
prev sibling parent Jacob Carlborg <doob me.com> writes:
On 2012-05-29 21:18, Sharp wrote:
 Hi all!

 I've spend several hours to solve my problem, and I did it!

 But don't know why it is worked in this way:
 I'd like to modify all fields of an object by a specific values (for
 deserialization).
If you want a serialization library: https://github.com/jacob-carlborg/orange -- /Jacob Carlborg
May 29 2012