Subclassing overloaded operators

Viewed 28

I have a class A overloading the + operator, and a class B inheriting from A. I'd like the sum of two instances of B to be an instance of B.

I'm able to do that only by overload the + operator in B, which I'd like to avoid. Is there a way to achieve that in Swift ?

class A {
    var a: Double
    init(_ a: Double = 0) { self.a = a }
    init(_ a: A) { self.a = a.a }
    static func +(_ lhs: A, _ rhs: A) -> A {
        A(lhs.a + rhs.a)
    }
}

class B : A {
    static func +(_ lhs: B, _ rhs: B) -> B {
        return B((lhs as A) + (rhs as A))   // I'd rather avoid this part
    }
}

func test() {
    let a1 = A(4)
    let a2 = A(2)
    let sa = a1 + a2   // typed to A
    
    let b1 = B(3)
    let b2 = B(2)
    let sb = b1 + b2  // typed to B
    
    let sa = a + b    // typed to A, which is OK
}

I looked into Self but it appears it can't be used a function parameters.

0 Answers
Related