Local static class fields

Bert Bert at gmail.com
Tue Aug 13 08:41:02 UTC 2019


On Tuesday, 13 August 2019 at 04:43:29 UTC, Paul Backus wrote:
> On Monday, 12 August 2019 at 22:48:43 UTC, Bert wrote:
>> Making a field static is effectively a global variable to the 
>> class.
>>
>> I have a recursive class structure(think of a graph or tree) 
>> and I need to keep a global state for it, but this state 
>> actually needs to be different for each tree object. The 
>> reason for this is that structurally it will not change per 
>> tree and if it it is not static then it wastes space 
>> unnecessarily.
>>
>> [...]
>>
>> Is there any way to do this more naturally in D?
>
> It seems to me like the obvious solution is to use two 
> different classes, one to store the global state, and one to 
> store the individual objects in your structure. For example:
>
> class Tree {
>     State state;
>     Node root;
> }
>
> class Node {
>     Node[] children;
> }

Yes, I forgot to mention this as a solution.

I was going to go in to more detail. This is not a great solution 
because it requires a base class simply to hold the "global" 
state and it requires nodes to have an accessor(they won't know 
which tree they come from).

What I was thinking though, with D's capabilities, if a 
constructor could somehow return a "Voldemort" type that makes it 
all work out.

e.g.,

class Tree {
     State state;
     Node root;
     alias root this;
}

then the constructor just returns tree which acts as an node.

It doesn't have to be a voldemort but it at least hides some of 
the details...

Ultimately it is not too different from using a dictionary 
though, effectively does the same thing.

The main issue with your solution is that Nodes themselves do not 
have access to the state directly and that is a similar issue 
with the dictionary. One has to traverse up to the root and then 
get the state, in your case, Tree would have to inherit from Node 
so it could be cast and be the root(else the Node would have to 
reference the tree).

There may be no way around such a problem in that these might be 
"optimal". Your's, which added parent in node, might be better 
since a dictionary doesn't have to be directly maintained.

I'd like to get away from actually having a different "root" type 
though. Mainly because it reduces uniformity and complicates the 
design I already have. If I could hide all these things and it is 
not too complicated then it would work better for me.





More information about the Digitalmars-d-learn mailing list