The point is just cause two generic parameters are related does not mean the
data type should support this conversion. `seq[Child] -> seq[Parent]` is just a
single instance of where it can be fine. I can provide a multitude of examples
where this implicit conversion causes runtime issues cause it's not desired.
This means that one would special case only `seq[T]` conversions, and even then
there are cases likely where one would not want this behaviour.
type MyChannel[T] = object
data: ref seq[T]
proc send[T](channel: var MyChannel[T], data: T) =
channel.data[].add data
type
Parent = ref object of RootObj
someField: float
Child = ref object of Parent
a: int
b: string
# Using your provided logic the following should be done implicitly by the
compiler
# Where generic instances are convertible in the case that the generic
parameters are implicitly convertible.
# `Child of Parent` holds so this should happen.
converter toParent(channel: MyChannel[Child]): MyChannel[Parent] =
cast[MyChannel[Parent]](channel)
var myChannel = MyChannel[Child](data: new seq[Child])
proc handle() =
for x in myChannel.data[]:
echo x[]
var myAlias: MyChannel[Parent] = myChannel
myAlias.send Child(someField: 120, a: 100, b: "hmm")
myAlias.send Parent(someField: 300)
myAlias.send Child(someField: 32, a: 320, b: "huh")
handle()
Run
Do not get me wrong there is some merit to converting generic instances to
their parent types, but that's why we have converters and concepts.
type
Parent = ref object of RootObj
someField: float
FromParent = concept fp
fp of Parent
Child = ref object of Parent
a: int
b: string
converter toParentSeq(s: seq[FromParent]): seq[Parent] =
cast[seq[Parent]](s)
converter toParentSeq(s: var seq[FromParent]): var seq[Parent] =
cast[seq[Parent]](s)
type MyNewChild = ref object of Child
var a: seq[Parent] = @[Child()]
a = @[MyNewChild()]
Run