Proposal: Implicit type conversion for structs
Jaak
jpdt at telkomsa.net
Wed Oct 25 08:25:28 PDT 2006
Hello
I propose the following extension to structs:
One can define methods for struct T of the type:
T opImplicitConvert(T2 t)
which allows the implicit conversion of variables of
type T2 to type T.
(the name itself is not important, others possibilities:
opImpConvFrom, opICast_r, etc.)
A conversion does no make sense if the types T2 and T
are the same, as that can cause an infinite chain
of conversions.
i.e. T opImplicitConvert(T t) is illegal
We now get opAssign semantics without breaking
or changing the way assignments currently work.
Example code:
struct Vector {
float[] elems;
...
Vector opImplicitConvert(float[] a)
{
Vector v;
v.elems = a.dup;
return v;
}
}
...
Vector u, v;
// Current system
u = v; // Currently OK
u = [1f 2f 3f]; // ERROR
// Proposed system
u = v; // Still OK
v = [1f 2f 3f]; // OK, as Vector.opImplicitConvert(float[]) exists
Some possible enhancements:
1. A smarter compiler may be able to figure out conversions chains if
a direct conversion is not possible.
I.e.
MyVector a;
YourVector b;
HisVector c;
// uses Vector.opImpConv(YourVector.opImpConv(HisVector)) if
// Vector.opImpConv(HisVector) does not exist
a = c;
2. If property syntax can be used to add methods to structs, one can do
the following:
Vector opImplicitConvert(Vector, OtherVector w) {
Vector t;
t.elems = w.elems;
return t;
}
// Then, variables of type OtherVector can be implicitly
// converted to type Vector. This is especially useful if
// the source implementing the struct Vector is not available.
OtherVector w;
v = w; // expands to v = v.opImplicitConvert(w);
Any comments?
-
Jaak
More information about the Digitalmars-d
mailing list