const after initialization / pointers, references and values
Wyatt via Digitalmars-d
digitalmars-d at puremagic.com
Fri Aug 22 13:12:38 PDT 2014
On Friday, 22 August 2014 at 18:21:06 UTC, Vicente wrote:
>
> @Wyatt:
> Certainly ref parameters help a lot, but I'm trying to get a
> "Node" by returning (a reference to) it. Does the ref keyword
> apply to the return type?
I poked it a bit and came out with this. I _think_ it's working
as expected:
import std.stdio;
import std.string;
// struct or class
struct Node {
Node[] block;
uint num = 0;
};
// static immutable
Node[] default_nodes = [
{num:3},
{block:[{num:4},{num:6},{block:[{num:5},{num:7}]}]},
// ...
];
class NodeProvider{
// change to const after constructor
private Node[] nodes;
private void parse_file(char[] file_name){
// initialize nodes from file
for(auto i=0; i<3; i++){
nodes.length++;
nodes[$-1].num=i;
}
}
this(){
nodes = default_nodes;
}
this(char[] file_name){
parse_file(file_name);
}
auto ref opSlice(){return nodes[];};
}
string NodetoString(ref Node n){
string str = format("%u{ ", n.num);
foreach(b;n.block)
str ~= NodetoString(b);
str ~= "} ";
return str;
}
int main(char[][] args){
NodeProvider np;
if(args.length==2)
np = new NodeProvider(args[1]);
else
np = new NodeProvider();
foreach(node_ref; np){
writeln(NodetoString(node_ref));
}
return 0;
}
-Wyatt
More information about the Digitalmars-d
mailing list