Re: Pointer to generic type with unspecified generic parameter?

2017-11-24 Thread coffeepot
Does the {.inheritable.} pragma convert an object into a pointer or keep it as 
a normal object with copy semantics?

Also, something to bear in mind, upon testing this it seems the type is erased 
when inserting into a seq: (Nim version 0.17.3 2017-10-13)


import typetraits

type
  Obj1 = object {.inheritable.}
a: int
  Obj2 = object of Obj1
b: float

var
  x = newSeq[Obj1]()

x.add Obj1(a: 1)
x.add Obj2(a: 2, b: 3.5) # This is allowed

echo x[1].type.name  # output Obj1, not Obj2
echo Obj2(x[1])  # This fails at run time with invalid object 
conversion, Obj2's extra fields are lost


Should the compiler warn that putting an Obj2 into a seq of Obj1 will drop it's 
extra data? Or is the extra data meant to be there but there's a bug somewhere?

With a ref, the type is obscured but internally preserved as expected:


import typetraits
type
  ARef1 = ref object of RootObj
a: int
  ARef2 = ref object of ARef1
b: float

var
  y = newSeq[ARef1]()

y.add ARef1(a: 1)
y.add ARef2(a: 2, b: 4.5)

# output ARef1, not ARef2 (probably because 'type' is compiletime)
echo y[1].type.name
# displays data as ARef2 as expected, data is preserved - assuming you can 
cast appropriately at runtime
echo ARef2(y[1]).repr



Re: Pointer to generic type with unspecified generic parameter?

2017-11-23 Thread Udiknedormin
@monster Why not use inheritance?


type
  ThreadID* = distinct uint8
  
  AnyMsg = object {.inheritable.}
sender*: ThreadID
receiver*: ThreadID
previous: ptr[AnyMsg]
  
  Msg*[T] = object of AnyMsg
content*: T

let space = alloc0(sizeof(Msg[int]))
let m = cast[ptr[Msg[int]]](space)
let p: ptr[AnyMsg] = m.previous