Reset class member variables
Regan Heath
regan at netmail.co.nz
Mon Sep 10 02:05:19 PDT 2007
mandel wrote:
> Hi,
>
> I have some big classes with lots of member variables
> that need to be reset to theire initial value.
> Therefore I thought about a more reliable way to
> accomplish this, because it's hard to keep track
> of variables I have added.
> It also looks bloated to assign all values manually.
>
> class Foo
> {
> uint x;
> char[] name = "world";
> //problematic:
> const uint y;
> char[1024] buffer;
>
> void reset()
> {
> scope tmp = new typeof(this);
> foreach(i, x; tmp.tupleof)
> {
> this.tupleof[i] = x;
> }
> }
> }
>
> The problem is that I have to avoid
> to try to set const values and static arrays.
>
> How can this be done?
How about putting the member variables you want to reset inside a struct
inside the class, eg.
import std.stdio;
class Foo
{
struct FooData
{
int a = 6;
}
FooData data;
int a() { return data.a; }
void reset() { data = FooData.init; }
}
void main()
{
auto f = new Foo();
writefln(f.a);
f.data.a = 5;
writefln(f.a);
f.reset();
writefln(f.a);
}
The proposed "alias data this" could later be used to bring the members
of FooData into the scope of Foo allowing you to access them as "f.a"
without property methods.
Regan
More information about the Digitalmars-d
mailing list