Accessing members through pointers to structs (also, CTFE associative arrays)

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Dec 13 15:29:31 PST 2016


On 12/13/2016 01:36 PM, Ali wrote:

> Now about that second part of my problem ....

I'm not entirely sure whether this should work but I think the problem 
is with mutating the 'frequencies' member of an immutable element of 
'rooms'. The error message means that those non-const expressions cannot 
be shared by a member of an immutable AA.

I moved the frequencies to 'data' and hte following worked. Used 'shared 
static this' so that the data is populated per application instead of 
per thread. Additionally, the 'd.room.name.writeln' expression works 
just fine with DMD64 D Compiler v2.072.1.

import std.algorithm: splitter, map;
import std.array: array;
import std.typecons: Tuple;
import std.stdio: writeln;

static immutable Room[] rooms = import("data.txt").splitter.map!parse.array;

struct Room {
     string name;
}

static Tuple!(const(Room*), "room", int[char], 
"frequencies")[rooms.length] data;

shared static this() {
     foreach (i, ref room; rooms) {
         data[i].room = &room;
         foreach (letter; room.name) {
             data[i].frequencies[letter]++;
         }
     }
}

Room parse(string line) pure {
     immutable name = line;
     return Room(name);
}

void main() {
     foreach (d; data) {
         d.room.name.writeln;
         d.frequencies.writeln;
     }
}

Ali



More information about the Digitalmars-d-learn mailing list