const AA require

Tejas notrealemail at gmail.com
Wed Aug 4 10:51:27 UTC 2021


On Wednesday, 4 August 2021 at 09:43:57 UTC, jfondren wrote:
> On Wednesday, 4 August 2021 at 08:08:35 UTC, Tejas wrote:
>> On Thursday, 29 July 2021 at 20:44:35 UTC, Elronnd wrote:
>>> const(int)[int] d;
>>> d.require(5, 7); //compile error
>>>
>>> From a semantics perspective, though, I don't think there's 
>>> anything wrong with this, and 'require' could reasonably cast 
>>> the const away before assigning.  Am I missing anything?
>>
>> Casting ```const``` away is undefined behaviour in D. And what 
>> is this "require"? Maybe show more code?
>
> what's wanted here is an assign-once hash table, I imagine.
>
> require is https://dlang.org/phobos/object.html#.require , and 
> it'd be the assignment line of that code that would have to 
> cast away const.
>
> ```d
> unittest {
>     int[int] nums;
>     nums.require(0, 0);
>     nums[0]++;
>     assert(nums == [0: 1]);
> }
>
> unittest {
>     const(int)[int] nums;
>     assert(__traits(compiles, nums.require(0, 0)));
>     assert(!__traits(compiles, nums[0]++));
> }
> ```

Well, OP will have to create non-const AA first and then cast it 
to const, it seems.

```d
import std;
void main()
{
     int[int] a;
     a.require(5,7);
     auto b = cast(const(int)[int])a;
}

```

Probably hide the process behind a function to make it look more 
smooth; otherwise I'm outta ideas.



More information about the Digitalmars-d mailing list