Skip to content

Commit

Permalink
✨ Add pick macro for handling runtime polymorphism
Browse files Browse the repository at this point in the history
  • Loading branch information
glassesneo committed Jul 1, 2024
1 parent 392a2f2 commit 8509b54
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 7 additions & 0 deletions src/oolib.nim
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,10 @@ macro isInstanceOf*(v: typed, T: typedesc): bool =
else:
`v`.type is `T`

macro pick*(t, P: untyped): tuple =
let tupleTy = ProtocolTable[P.strVal]
result = nnkTupleConstr.newTree()
for v in tupleTy:
let name = v[0]
result.add newColonExpr(name, t.newDotExpr(name))

11 changes: 8 additions & 3 deletions tests/implementation.nim
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ class HTMLWriter impl Writer:

let book = Book.new(price = 500)

let _ = book.toProtocol()

let diary = Diary.new(price = 300)

let _ = diary.toProtocol()
var products: seq[Product] = @[]

products.add book.toProtocol().pick(Product)

products.add diary.toProtocol().pick(Product)

for product in products:
echo product.price

0 comments on commit 8509b54

Please sign in to comment.