generic + numeric + literals = abomination
biozic
dransic at free.fr
Sat Mar 27 10:39:30 PDT 2010
Le 27/03/10 18:18, so a écrit :
> With this in mind, just one thing bugs me.
>
> ----
> import std.stdio;
>
> struct vector(T) {
> this(T m) { mm = m; }
> vector!T opBinary(string s)(T m) if(s=="*") {
> return vector!T(mm * m);
> }
> T mm;
> }
>
> void test(T)() {
> vector!T v = vector!T(0.5);
> vector!T u = v * 0.3;
> writeln("u: ", u.mm);
> }
>
> void main() {
> test!float();
> test!double();
> test!real();
> }
> -----
>
> This program compiles and runs just fine, but i feel dirty, you see I
> explicitly stated that opBinary takes a variable of type T,
> but it accepted 0.3 on all 3 tests, implicitly casted double to T. In
> C++ world this brings tons of trouble, especially performance problems,
In this case, when is(T==real), you could have a precision problem more
than a performance problem. You lose less precision if you always use
literals of the most precise type (eg 0.3L).
Performance problems could occur in C++ when your template type is 'long
double' (?). But then if 'double' is the most efficient type and if you
want performance, use it explictly everywhere.
More information about the Digitalmars-d-learn
mailing list