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/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to