Le 30/01/2013 17:49, Namespace a écrit :
Is the compiler (dmd) fit enough to detect and avoid unnecessary casts?
E.g.
[code]
void foo(T)(T num) {
int f = cast(int) num;
// ...
}
foo(42); // cast is unnecessary
foo(4.2); // cast is necessary
[/code]
Or should I wrote everytime
[code]
void foo(T)(T num) {
static if (is(T == int) || isImplicitlyConvertible!(T, int)) {
int f = num;
} else {
int f = cast(int) num;
}
// ...
}
[/code]
Until now I count on the compiler, that it detect this cases and avoid
casts. But I'm not 100% sure, so I want to ask.
When the template gets instantiated, the compiler has to determine what
"cast(int)" exactly means for type T ; if T is int, the obvious answer
is to do nothing, so I don't see a problem. Just my guess.