I'm exploring the use of concepts and wondering if there is a way to implement something like what I have below.
type
Base = concept b
b.base is string
Additional = concept a
a.additional is string
type
MyBase = object
base: string
MyAdditional = object
base: string
additional: string
proc addToString(o: Additional, s: var string) =
s.add(", " & o.additional)
proc getString(o: Base): string =
result.add(o.base)
addToString(o, result) # How to call this only for types that satisfy the MyAdditional concept?
var
myAdditional = MyAdditional(base:"base", additional:"additional")
myBase = MyBase(base:"base")
echo getString(myAdditional)
echo getString(myBase)
Obviously getString(myBase) doesn't work. But is there some automated way to create something like this at compile time where a proc is only called if an object matches some concept? I have some code like this already that uses generics and mixins. I'm wondering if I can use concepts and have more flexibility.
You can simply modify your getString proc to something like this:
proc getString(o: Base): string =
result.add(o.base)
when typeof(o) is Additional:
addToString(o, result) # How to call this only for types that satisfy the MyAdditional concept?
Just because getString takes a Base does not mean you can't check if it's also an Additional. :)