I made an object SEQ[T] which member has data of type seq[T]. Also, I want [] operator and converter from SET[T] to seq[T]. Then, it seems that the data cannot rewrite in proc f of result.data[0] += 1. But this operation is not related to converter or [] operator because result.data is seq[T] and accessing [0] is only access of seq[T]. I think, result.data is converted to SEQ[T]. I don't want to the converter activated in this case. Then, how to do it?
type SEQ*[T] = object
data*:seq[T]
proc initSEQ*[T](n:int):SEQ[T] =
SEQ[T](data:newSeq[T](n))
# [] operator
proc `[]`*[T](self:SEQ[T], i:int):T = self.data[i]
# converter
converter toSEQ*[T](a:seq[T]):SEQ[T] =
SEQ[T](data:a)
proc f*[T](a:SEQ[T]):SEQ[T] =
result = a
result.data[0] += 1 # I don't like to converter activated
when isMainModule:
var a:SEQ[int] = @[1, 2, 3] # I want to define this way by converter
echo f(a)
I wouldn't recommend using converter as it makes your code less readable and can often create ambiguity when compiling, especially for something as trivial as an assignment.
You could rewrite your code as this :
type SEQ*[T] = object
data*: seq[T]
proc asSEQ*[T](x: seq[T]) : SEQ[T] =
result.data = x
proc initSEQ*[T](n: int): SEQ[T] =
SEQ[T](data: newSeq[T](n))
# [] operator
proc `[]`*[T](self: SEQ[T], i: int): T =
self.data[i]
proc `[]=`*[T](self: var SEQ[T], i: int, val: T) =
var d = self.data
d[i] = val
# No need to return a if passed as a var parameters
proc f*[T](a: var SEQ[T]) =
a[0] = 1
when isMainModule:
var a: SEQ[int] = @[1, 2, 3].asSEQ # I want to define this way by converter
f(a)
echo a[0]