How do I store an immutable value into a mutable associative array?
Ali Çehreli
acehreli at yahoo.com
Tue Nov 6 10:25:45 PST 2012
On 11/06/2012 09:48 AM, PlatisYialos wrote:
> On Tuesday, 6 November 2012 at 17:23:41 UTC, PlatisYialos wrote:
>
> Errmm! Here's a better example, but with the same results:
>
> ----------------------------
> module test;
>
> void noparens() {
> immutable char[char] aMap;
> char a = 'a';
> immutable char b = 'b';
> aMap[a] = b;
> }
>
> void withparens() {
> immutable(char)[char] aMap;
> char a = 'a';
> immutable char b = 'b';
> aMap[a] = b;
> }
> -----------------------------
>
I think it is not surprising why noparens() doesn't work: aMap is immutable.
withparens() would be expected to work but again, 'aMap[a] = b' is seen
as a mutation of element aMap[a]. If associative arrays had an insert()
function, then we would expect it to work.
Here is a quick solution:
/* I used 'inout' to accept mutable, const, and immutable value types */
void insert(K, V)(ref immutable(V)[K] aa, K key, inout V value)
{
/* I would like to use the following simpler code:
*
* auto mutable = cast(V[K])aa;
* mutable[key] = value;
*
* It did not work when 'aa' was null. The later initialization of
* 'mutable ' would affect only 'mutable', not 'aa'.
*/
V[K] * mutable = cast(V[K]*)&aa;
(*mutable)[key] = value;
}
// ...
aMap.insert(a, b);
Ali
More information about the Digitalmars-d-learn
mailing list