difficulties with const structs and alias this / template functions

Dennis dkorpel at gmail.com
Sun Nov 18 20:10:52 UTC 2018


On Sunday, 18 November 2018 at 18:17:54 UTC, Stanislav Blinov 
wrote:
>         // implement separate methods for 
> mutable/const/immutable

Thanks. I should have tried that, but I assumed it wouldn't work 
since you can't overload on return-type only. However, the const 
/ non-const makes it allowed.

> Or like this:
>
>         // implement all three in one method, using the `this 
> template` feature

That's new to me, interesting.

> Define different overloads for Q and const Q. Or this:
>
> Q log2(Q)(inout Q num) if (is(Q : q16) || is(Q : q32)) { /* ... 
> */ }
>
> Being able to jam mutable/const/immutable implementation in one 
> function like that should tell you that you shouldn't mutate 
> the argument. Then, the necessity to Unqual will go away on 
> it's own ;)

Different overloads sounds like a lot of boilerplate.
inout still results in "cannot modify `inout` expression `input`"
My goal is to be able to write straightforward and correct 
signatures for fixed point functions that receive mutable copies 
of whatever they are fed. This isn't even limited to my custom 
types:

```
T f0(T)(T x, T y) {return x += y;}
int  f1(int  x, int  y) {return x += y;}
long f1(long x, long y) {return x += y;}

void main()
{
     import std.stdio;
     writeln(f0(const(int)(3), const(long)(4))); // can't modify 
const
     writeln(f1(const(int)(3), const(long)(4))); // fine
}
```
The explicit overloads of f1 work fine, but the generic f0 does 
not. I could just use the f1 strategy of explicitly making 
overloads, but then adding a q64 or q128 type would mean having 
to double the existing boilerplate everywhere. I would like to 
have a `isFixedPoint` template and generic functions that take 
any isFixedPoint!Q, but it seems I have to manually enforce 
"don't forget to unqual Q first!".



More information about the Digitalmars-d-learn mailing list