Is there a default initializer that is called when an object is constructed and
that can be overloaded?
I have a chicken and egg problem about initializing a generic data structure.
In data structure `module1.nim`, I need to initialize a generic parameter and I
forward declare the `initElement[T]: T` proc so that a data structure can call
it and the client using that module will be able to initialize her objects:
type
MyType[T] = object
... complex data structure...
# Forward initializer
proc initElement*[T]: T
proc foo[T]: T =
# Here I need to initialize T
result = initElement[T]()
... do something on T
Run
In client module, where `T` is instantiated, the client must define the
`initElement: TypeInstance` proc but the compiler now says that `overloaded
'initElement' leads to ambiguous calls`:
import module1
type
TypeInstance = object
... complex type that must be initialized
proc initElement: TypeInstance =
# Initialize correctly the type
result = doCalculations()
Run
Is there a pattern in order to delegate initialization to the user of a module?
A bit like when using `Table[K, V]`, the client must define `hash` and `==` for
the key type.
I could require passing a proc pointer to the initializer in the generic
module, but I would like to use naming/overloading resolution instead as the
interface will be simpler for the clients.
Initializing objects are required when [defaults
values](https://nim-lang.org/docs/manual.html#statements-and-expressions-var-statement)
are not acceptable and create invalid objects. For instance, when default
values are the result of complex calculations, or simply when `'\0'` is not
valid default character.
I've tried using
[concepts](https://nim-lang.org/docs/manual_experimental.html#concepts) too but
did not got a correct result.