Why do I have to cast arguments from int to byte?
rjframe
dlang at ryanjframe.com
Wed Oct 11 00:43:40 UTC 2017
On Tue, 10 Oct 2017 19:55:36 +0000, Chirs Forest wrote:
> It wouldn't be so bad if I didn't have to use the word cast before each
> cast, bust since I have to specify both the word cast and the cast type
> and then wrap both the cast type and the value in brackets... it just
> explodes my code into multiple lines of unreadable mess.
>
>
> void foo(T)(T bar, T bar2, T bar3){...}
>
> byte foobar = 12;
>
> foo!byte(foobar + 1, foobar + 22, foobar + 333);
> vs.
> foo!byte(cast(byte)(foobar + 1), cast(byte)(foobar + 22),
> cast(byte)(foobar + 333));
You could wrap the cast in a function to clean it up a bit:
void main() {
byte foobar = 12;
foo!byte((foobar + 1).b, (foobar + 22).b, (foobar + 333).b);
}
byte b(int n) pure {
pragma(inline, true); // Probably not necessary.
return cast(byte)n;
}
void foo(T)(T bar, T bar2, T bar3) {
import std.stdio : writeln;
import std.string : format;
writeln("%s, %s, %s".format(bar, bar2, bar3));
}
--Ryan
More information about the Digitalmars-d-learn
mailing list