Code duplication where you wish to have a routine called with either immutable or mutable arguments

Cecil Ward cecil at cecilward.com
Wed May 31 03:29:33 UTC 2023


On Wednesday, 31 May 2023 at 03:23:01 UTC, Cecil Ward wrote:
> On Tuesday, 30 May 2023 at 04:15:22 UTC, Ali Çehreli wrote:
>> On 5/29/23 19:57, Cecil Ward wrote:
>>
>> > I wish to have one routine
>> > that can be called with either immutable or (possibly)
>> mutable argument
>> > values.
>>
>> 'const' should take both immutable and mutable. Can you show 
>> your case with a short example?
>>
>> > Could I make the one routine into a template?
>>
>> That could work but give 'in' parameters a try:
>>
>>   https://dlang.org/spec/function.html#in-params
>>
>> Ali
>
> T2 foo( in T1 x ) { return bar( x ) };
>
> It was with something vaguely like the above that I had to 
> remove the in (templatised generic function possibly) in order 
> to get it to compile with GDC or LDC on godbolt.org (or 
> d.godbolt.org) latest versions available. -O3 
> -release/-frelease -march=native/-mcpu-native

I have to admit that I don’t really understand immutable. I have 
an idea that it could mean that an object has an address in ROM, 
so its value will never change. Maybe const doesn’t give you such 
a strong guarantee, disallows ‘you’ from modifying it but others 
might do so, but who knows. Without a guarantee as strong as the 
first idea I can’t really understand how const can work properly. 
"You treat it as const so do not modify it, but it might not be 
eternally fixed and  unchanging" that doesn’t seem to have enough 
value to me. But maybe I’ve got the whole thing wrong.

In an architecture where you have strongly typed (tagged ? 
segmented?) different kinds of addresses, I can see why you might 
be getting type mismatch errors when passing addresses around.


More information about the Digitalmars-d-learn mailing list