I'm trying to do the following
type Foo{T}
x::changeType(T)
end
where the function changeType changes the type parameter to some other type. It doesn't have to be a function, I'm happy using a dictionary or a macro or w/e, I just need a way to do this.
I tried it with both a function and a dictionary and both resulted in errors.
I believe this is not entirely possible. However, you can play with a couple of workarounds.
Do not constrain the type of
xand just instantiatexwith the proper type manualy:You can wrap your object in a function:
Then create an object of
FooIf you want to have mixed type fields in the same
type(e.g. fields ofTandmap(T)) you can modify a bit the constructor:This will allow you to create
FooasFoo{Int64}while mappingxtoFloat32:And the last, and probably the most viable one: first define the dictionary and wrap your
typein bothtypes:Now wrap the construction of a
Fooobject into a function:foofunction creates objects of typeFoowhere the first parameter specifies the typeTofFooand the typeVis dynamically inferred from thetypesdictionary.Note: in both the above methods, if
Tis not defined in thetypesdictionary, thegetfunction returnsTand thusxis mapped toT. Is a fall-back method for types that don't require mapping. E.g. for the third option:both
xandyareInt32sinceInt32is not in the mapping dicttypes. And for the fourth option:I think currently the type of
xcannot be specified at compile time as a function ofT, but the above workarounds should do the job.I don't know neither how smart is the Julia compiler.. given that the
typesdictionary is constant, it might do some smart things and infer the type ofxfrom there (maybe a dev could answer this or give further improvements).