alternative fake covariance based on converters

This commit is contained in:
Zahary Karadjov
2017-04-28 18:26:33 +03:00
parent 72f42ff95f
commit 5c678e2848
2 changed files with 25 additions and 3 deletions

View File

@@ -35,8 +35,8 @@ reject wantsSpecificContainers(derived)
# Now, let's make a more general solution able to catch all derived types:
type
DerivedFrom[T] = concept type A
var derived: ref A
DerivedFrom[T] = concept type D
var derived: ref D
var base: ref T = derived
proc wantsDerived(x: DerivedFrom[BaseObj]) = discard
@@ -54,3 +54,25 @@ accept wantsDerivedContainer(derivedContainer)
reject wantsDerivedContainer(nonDerivedContainer)
# The previous solutions were solving the problem for a single overload.
# Let's solve it for multiple overloads by introducing a converter:
type
OtherContainer[T] = object
proc wantsBaseContainer1(c: OtherContainer[BaseObj]) = discard
proc wantsBaseContainer2(c: OtherContainer[BaseObj]) = discard
converter derivedToBase(c: OtherContainer[DerivedFrom[BaseObj]]): OtherContainer[BaseObj] = discard
block:
var baseContainer: OtherContainer[BaseObj]
var derivedContainer: OtherContainer[DerivedObj]
var nonDerivedContainer: OtherContainer[NonDerivedObj]
accept wantsBaseContainer1(derivedContainer)
reject wantsBaseContainer1(nonDerivedContainer)
accept wantsBaseContainer2(derivedContainer)
reject wantsBaseContainer2(nonDerivedContainer)

View File

@@ -10,7 +10,7 @@ proc newMutableArrayAbstract*(): NSMutableArrayAbstract = discard
template newMutableArray*(T: typedesc): NSMutableArray[T] =
cast[NSMutableArray[T]](newMutableArrayAbstract())
proc writeObjects*(p: NSPasteboard, o: ptr NSArray[NSPasteboardItem]) = discard
proc writeObjects*(p: NSPasteboard, o: NSArray[NSPasteboardItem]) = discard
let a = newMutableArray NSPasteboardItem
var x: NSMutableArray[NSPasteboardItem]