Hello everyone,
I have a function that looks like this:
proc returnZero[T]() : T =
return T(0)
and I would like to provide a default implementation that doesn't not require to call the T type, defaulting it to float64.
The call would look like:
let val = returnZero() #returns a float64, instead of typing returnZero[float64]()
I have tried to implement a secondary proc to do so, but the compiler complains about ambiguous calls:
proc returnZero() : float64 =
return float64(0)
Is there a way to achieve this?
Try this:
proc returnZero(T: typedesc = typedesc[float64]): T = T(0)
discard returnZero(int)
discard returnZero()
Although you might want to use system.default[T]() instead
Thanks for the answer.
The system.default() is a nice option, but the code I proposed was only a minimal example, in my real case I don't need to return a zero.
Regarding the option you proposed, I only have the problem that I would still like to maintain the
let val = returnZero[int]()
syntax for values that are not the default.
Dumb question.. wouldn't it then make sense to define your "default type proc"?
proc returnZero[T]() : T =
return T(0)
proc returnZeroDefault() : float =
return returnZero[float]()
echo returnZeroDefault()
echo returnZero[int]()
I just realized that this syntax seems to compile, even if it doesn't work:
proc returnZero[T = float]() : T =
return T(0)
Will this syntax work in the future? I think it is quite neat in its separation between types and values, opposed to the typedesc implementation.