Why code failed to compile for foo2?
Tejas
notrealemail at gmail.com
Mon Dec 13 08:41:28 UTC 2021
On Sunday, 12 December 2021 at 03:02:28 UTC, apz28 wrote:
> On Sunday, 12 December 2021 at 00:02:25 UTC, Stanislav Blinov
> wrote:
>> @apz28, I can't figure out the intent here. To convert result
>> of abs to an unsigned?
>
> The function logic works only for unsigned type and the
> parameter value can be altered in body hence Unqual. If not
> Unqual, must declare a local var and make a copy. Just asking
> if this can be done to avoid a cast by caller
AFAIK stuff like `const int` implicitly converts to `int` since
`int` is passed by value so the `const`ness of the original value
is not violated.
That's why code like:
```d
void main(){
const int a = 55;
int b = a;
}
```
compiles and executes.
So, in a similar vein, your code will transform to:
```d
void foo1(ubyte x) {}
void foo1(ushort x) {}
void foo1(uint x) {}
void foo1(ulong x) {}
import std.traits : Unconst;
import std.stdio : writeln;
void foo2(T)(T x) if(is(Unconst!(T) : ulong)) {//You don't need
Unqual for this
foo3(x);
}
void foo3(ulong param){ //I'm assuming this is your function that
you will pass your uint to
writeln(param);
}
void main()
{
import std.math;
int s = int.min + 1; //abs returns int.min for abs(int.min)
lol XD
foo1(abs(s));
foo2(abs(s)); //failed? //Not anymore :D
}
```
Again, please remember that `std.math.algebraic:abs` doesn't
return `uint` for `int` and so on, please see [the
documentation](https://dlang.org/phobos/std_math_algebraic.html#.abs):
>Returns:
>>The absolute value of the number. If floating-point or
>>integral, the __return type__ will be the __same as the input__.
>Limitations
>>Does not work correctly for signed intergal types and value
>>Num.min.
More information about the Digitalmars-d-learn
mailing list