How can I create a constructor for a parametric type using its abstract supertype?
This is my minimal nonworking example
abstract type MyNumber{T1<:Integer,T2<:Integer} end
struct MyNumber1{T1,T2} <: MyNumber{T1,T2}
a :: T1
b :: T2
end
struct MyNumber2{T1,T2} <: MyNumber{T1,T2}
a :: T1
b :: T2
end
function (::Type{MT})(a::T1,b) where {T1 <: Integer, MT<:MyNumber{T1}}
println("here?")
end
MyNumber1{Int}(1,2)
the error message is:
julia> MyNumber1{Int}(1,2)
ERROR: MethodError: no method matching (MyNumber1{Int64, T2} where T2)(::Int64, ::Int64)
Stacktrace:
[1] top-level scope
@ REPL[10]:1
if I write it as a Union like:
function (::Type{MT})(a::T1,b) where {T1 <: Integer, MT<:Union{MyNumber1{T1}, MyNumber2{T1}}}
println("here?")
end
it works though.
Appreciate any help and explanation why this doesn’t work.
Thanks a lot. I’ve never seen a where inside a where before
I was wondering why I need to specify all of the types of the parametric type (so T1 and T2) in general.
julia> abstract type MyNumber{T1<:Integer,T2<:Integer} end
julia> struct MyNumber1{T1,T2} <: MyNumber{T1,T2}
a :: T1
b :: T2
end
julia> MyNumber1(1,2)
MyNumber1{Int64,Int64}(1, 2)
edit: I see that the definition of that function complicates things, sorry.
Sorry my example is a bit contrived. In my actual example I have some parts in the parametric fields (don’t know how to call them ) which can’t be extracted from the values of the function. Therefore I need to give T1 but T2 can be taken from the input. Hope that makes sense.