Hi,
I was wondering if having access to copy hook that takes a second argument of a different type was a good idea or not. Something like :
proc `=copy`(foo: var Foo, bar: Bar) =
foo.value = bar.value
In C++ you can define assignment operator for a Class Foo that takes a class Bar.
Foo& operator=(const Bar& other) {
value = other.value;
return *this;
}
It would be useful when mapping multiple possible types without resorting to inheritance (we don't want polymorphism) or Converter (could lead to ambiguity between procs). It's also useful when wrapping C++ library that uses this mechanism.
Should Nim have it as well ? What are the reason to NOT want this ?
What are the reason to NOT want this ?
How does this work for "lifted" assignment operators, for example, what if Foo is used inside a tuple type?
it could be equivalent to having a converter(Bar):Foo that is restricted to the parameters of =copy
current behaviour of converter with nested types:
type Foo = object
type Bar = object
converter toFoo(b:Bar):Foo = discard
let x = Foo()
let y:Bar = x #allowed
let z:(Bar,Bar) = (x,x) #error type mismatch
> How does this work for "lifted" assignment operators, for example, what if Foo is used inside a tuple type?
Anything expanded to a direct = assignment should work. Everything else shouldn't.
Converter are neat but often create ambiguous call between proc. Sometimes all you need it is = to be overloaded.
So maybe it should = that is able to overloaded and leave =copy as copy operator To quote @Clybber on nim#science :
I renamed = to =copy so that we would eventually be able to overload = like that reducing the need for converters
Which I assume would translate to this
# Okay to have for assignment operation
proc `=`(foo: var Foo, bar: Bar) =
foo.value = bar.value
# =copy still limited
proc `=copy`(foo: var Foo, fooz: Foo) =
foo.value = fooz.value
For context, the topic came from mapping C++ function which has a parameter like this torch::optionnal<T> = torch::nullopt - nullopt being an instance of nullopt_t and not an optionnal type.
In C++, it is implemented through an assignment operator that is overloaded.
There is no sub-type / inheritance relation between nullopt_t and optionnal
The only option available is to have multiple Nim proc overloaded for each default parameter value in C++.
This is not ideal because :