File: tfakecovariance.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (78 lines) | stat: -rw-r--r-- 2,266 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
template accept(x) =
  static: assert(compiles(x))

template reject(x) =
  static: assert(not compiles(x))

type
  BaseObj = object of RootObj
  DerivedObj = object of BaseObj
  NonDerivedObj = object

  Container[T] = object

var base: BaseObj
var derived: DerivedObj
var nonDerived: NonDerivedObj

var baseContainer: Container[BaseObj]
var derivedContainer: Container[DerivedObj]
var nonDerivedContainer: Container[NonDerivedObj]

# We can fake covariance by listing some specific derived types that
# will be allowed with our overload. This is not a real covariance,
# because there will be multiple instantiations of the proc, but for
# many purposes, it will suffice:

proc wantsSpecificContainers(c: Container[BaseObj or DerivedObj]) = discard

accept wantsSpecificContainers(baseContainer)
accept wantsSpecificContainers(derivedContainer)

reject wantsSpecificContainers(nonDerivedContainer)
reject wantsSpecificContainers(derived)

# Now, let's make a more general solution able to catch all derived types:

type
  DerivedFrom[T] = concept type D
    var derived: ref D
    var base: ref T = derived

proc wantsDerived(x: DerivedFrom[BaseObj]) = discard

accept wantsDerived(base)
accept wantsDerived(derived)

reject wantsDerived(nonDerived)
reject wantsDerived(baseContainer)

proc wantsDerivedContainer(c: Container[DerivedFrom[BaseObj]]) = discard

accept wantsDerivedContainer(baseContainer)
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)