Reputation: 13316
Assume the following setup:
class BaseClass<T> { }
class SubClass<T>: BaseClass<T> { }
infix operator >-- { associativity left }
func >-- <T>(lhs: BaseClass<T>, rhs: SubClass<T>) {
// do something here
}
What I am looking for is a way to exclude SubClass
from being used as the lhs
argument with the operator >--
. It would be kind of a negative type constraint on a generic argument - i.e., T: BaseClass where T != Subclass
:
func >-- <T, B: BaseClass<T> where B != SubClass<T>>(lhs: B, rhs: SubClass<T>)
But it does not appear that there is a !=
argument that you can supply as a negative type constraint for a generic. Is there a way to do this?
Thanks!
EDIT:
I think I can actually make the question less complicated - I think the following setup gets at exactly the same issue but without some distracting details:
class BaseClass { }
class SubClass: BaseClass { }
// This is what I want to be able to do, but don't know how
// or if it is possible:
func doSomething<B: BaseClass where B != SubClass>(arg: B) { }
Hope I didn't just confuse everyone more, but the "infix operator" part and the fact that BaseClass
was a generic BaseClass<T>
aren't really important to the question...
Upvotes: 3
Views: 740
Reputation: 535229
You cannot prevent substitution of subclass instance for superclass instance at compiler level, as you are trying to do, because that substitution is the basis of polymorphism itself.
You are, of course, free to throw a wobbly at runtime if the dynamicType
of the parameter turns out not to be the superclass:
func doSomething(arg: BaseClass) {
if !(arg.dynamicType === BaseClass.self) {
fatalError("die die die")
}
println("ok")
}
Upvotes: 1