difficulties with const structs and alias this / template functions

Stanislav Blinov stanislav.blinov at gmail.com
Mon Nov 19 02:31:00 UTC 2018


On Monday, 19 November 2018 at 02:03:18 UTC, Dennis wrote:
> 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.

Yes, but that's not the problem with your type. It's a problem 
with the user not realizing that const is a type qualifier.

> 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?

You're right, it's not needed there at all.

> 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.

Because, as before, value types are all copyable between 
mutable/const/immutable. So even if `return x + y` would yield a 
`const T`, you can still instantiate a T from it.



More information about the Digitalmars-d-learn mailing list