difficulties with const structs and alias this / template functions
Dennis
dkorpel at gmail.com
Mon Nov 19 02:03:18 UTC 2018
On Monday, 19 November 2018 at 01:13:29 UTC, Stanislav Blinov
wrote:
> You just dismissed that second to last sentence, did you? :)
I don't know what you mean with it. It's not that I'm trying to
be sneaky or lazy really trying to modify the const parameter
when I should treat it properly. And as the author I'm fine with
Unqualing everything if that's needed, my concern is when another
person using my type tries to write his own function:
```
q16 pow(q16 base, int exponent) {
q16 result = 1;
foreach(i; 0..exponent) result *= base;
return result;
}
const q16 x = 3;
writeln(pow(x, 3)); //works!
```
He then wants to make it more generic, so he rewrites:
```
Q pow(Q base, int exponent) if (isFixedPoint!Q) {
Q result = 1;
foreach(i; 0..exponent) result *= base;
return result;
}
```
And initially it seems to work, but as soon as it is used with
const it breaks as `result` can't be mutated anymore. I'd like to
set the example of writing proper generic functions, and if there
is something simpler than importing Unqual I'd prefer that over
my current solution. If there isn't, I'll just need to write a
"don't forget to Unqual const" comment.
> ```
> T f0(T)(inout T x, inout T y) { return x + y; }
> ```
>
> ;)
What does inout do here? If the return type is also inout(T) I
know that the return type gets the same qualifiers as inout
parameters. But in this example, the return value is still T.
> I know it's a bit painful though. In fact, Phobos also suffers
> from it. In std.numeric:
Yuck!
More information about the Digitalmars-d-learn
mailing list