This is a problem that seems to come up a lot in swift (they really need something like “IntegerArithmeticType” that includes floats, doubles, CGFloats, etc… so we don’t have to cast for simple arithmetic).
I think the trick that IntegerArithmeticType uses is that it has a common form that everything can be transformed into (i.e toIntMax() ). You could mimic this by turning everything into a double (or an NSDecimalNumber if you care more about precision than speed) for cases where the type doesn’t match. Someone else may have a more elegant answer... Thanks, Jon > On Jun 24, 2015, at 12:19 PM, Rick Mann <rm...@latencyzero.com> wrote: > > I've been experimenting with Swift 2, and have started writing a generic > Vector3<T> class. It looks something like this: > > ----- > protocol > VectorElementType: IntegerLiteralConvertible > { > func +(a: Self, b: Self) -> Self > } > > struct > Vector3<T where T: VectorElementType> > { > init() > { > x = 0; > y = 0; > z = 0; > } > > init(_ inX: T, _ inY: T, _ inZ: T) > { > x = inX > y = inY > z = inZ > } > > var x: T > var y: T > var z: T > } > > func > +<T>(inLeft: Vector3<T>, inRight: Vector3<T>) > -> Vector3<T> > { > return Vector3<T>(inLeft.x + inRight.x, inLeft.y + inRight.y, inLeft.z > + inRight.z) > } > > > extension Float: VectorElementType {} > extension Double: VectorElementType {} > > typealias Vector3f = Vector3<Float> > typealias Vector3d = Vector3<Double> > ----- > > The thing I'd like to do is let the + operator support two different types of > Vector3, such that if the individual VectorElementTypes are addable together > (either because a + operator exists for both types, or because one type can > be promoted to a type that can add), then it all "just works". > > In C++, this works because template instantiation happens when the types are > introduced, but in Swift, I have to promise that the types will work out that > way. But I've not figured out how. > > E.g., I can't do this: > > var a = Vector3d(1, 2, 3) > var b = Vector3f(4, 5, 6) > > var c = a + b > > How might I accomplish this? Thanks! > > > -- > Rick Mann > rm...@latencyzero.com > > > > _______________________________________________ > > Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) > > Please do not post admin requests or moderator comments to the list. > Contact the moderators at cocoa-dev-admins(at)lists.apple.com > > Help/Unsubscribe/Update your Subscription: > https://lists.apple.com/mailman/options/cocoa-dev/jhull%40gbis.com > > This email sent to jh...@gbis.com _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com