Hello,
Is it possible to implement a concept for overloaded functions?
This code works (prints "true"):
type
A = concept x
size(x) is int
read(x, int) is int
B = object
proc size(self: B): int =
return 0
proc read(self: B, size: int): int =
return 0
echo B() is A # true
But what if I wanted to use two possible read() signatures ? The following won't work.
type
A = concept x
size(x) is int
read(x, int) is int
read(x, string) is int
B = object
proc size(self: B): int =
return 0
proc read(self: B, size: int): int =
return 0
echo B() is A # false
Thanks, Howe
This works:
type
A = concept self
self.size is int
self.read(int) is int
when compiles self.read(string):
self.read(string) is int
type
B = object
C = object
proc size(self:B|C): int = 1
proc read(self:B|C, size:int): int = 2
proc read(self:B, text:string): int = 3
echo B is A # true
echo C is A # true
At some point in the future though, it would be cool to have more elegant syntax like:
type
A = concept self
self.size is int
self.read(int|string) is int
Hello @filwit.
Unhappily it does not work as I intended; I want the read method to accept read(self, string) OR read(self, int). Your suggestion demands (self, int) and allows an optional (self, string). The following example should print true, because the read(self, string) signature is satisfied:
type
A = concept self
self.size is int
self.read(int) is int
when compiles self.read(string):
self.read(string) is int
type
B = object
proc size(self: B): int = 1
#proc read(self:B, size:int): int = 2
proc read(self:B, text:string): int = 3
echo B is A # false
I had even tried second form (int|string), but indeed it didn't work.
@Araq is there any way to connect concepts using "or" ?
Thanks, Howe
What about:
type
A = concept self
self.size is int
when compiles self.read(int):
self.read(int) is int
when compiles self.read(string):
self.read(string) is int
when (not compiles self.read(int)) and (not compiles self.read(string)):
false
# xor even...
#when (compiles self.read(int)) and (compiles self.read(string)):
# false
type
B = object
proc size(self: B): int = 1
#proc read(self:B, size:int): int = 2
proc read(self:B, text:string): int = 3
echo B is A # true