generics - Limit function parameter argument to base class in Swift -
assume following setup:
class baseclass<t> { } class subclass<t>: baseclass<t> { } infix operator >-- { associativity left } func >-- <t>(lhs: baseclass<t>, rhs: subclass<t>) { // here } what looking way exclude subclass being used lhs argument operator >--. kind of negative type constraint on generic argument - i.e., t: baseclass t != subclass:
func >-- <t, b: baseclass<t> b != subclass<t>>(lhs: b, rhs: subclass<t>) but not appear there != argument can supply negative type constraint generic. there way this?
thanks!
edit:
i think can make question less complicated - think following setup gets @ same issue without distracting details:
class baseclass { } class subclass: baseclass { } // want able do, don't know how // or if possible: func dosomething<b: baseclass b != subclass>(arg: b) { } hope didn't confuse more, "infix operator" part , fact baseclass generic baseclass<t> aren't important question...
you cannot prevent substitution of subclass instance superclass instance @ compiler level, trying do, because substitution basis of polymorphism itself.
you are, of course, free throw wobbly at runtime if dynamictype of parameter turns out not superclass:
func dosomething(arg: baseclass) { if !(arg.dynamictype === baseclass.self) { fatalerror("die die die") } println("ok") }
Comments
Post a Comment