Parametric types help

This does work:

abstract type AbstractBar end

struct Foo{T <: Real,V <: AbstractBar}
    bar::Vector{V}
    t::Vector{T}
end

struct Bar <: AbstractBar
    b::Float64
end

Foo{T}() where {T} = Foo{T,Bar}(Bar[], T[])
Foo() = Foo{Float64,Bar}(Bar[], Float64[])
julia> Foo()
Foo{Float64,Bar}(Bar[], Float64[])

julia> Foo{Int64}()
Foo{Int64,Bar}(Bar[], Int64[])

This does not work:

abstract type AbstractBar end

struct Foo{V <: AbstractBar, T <: Real}
    bar::Vector{V}
    t::Vector{T}
end

struct Bar <: AbstractBar
    b::Float64
end

Foo{T}() where {T} = Foo{Bar,T}(Bar[], T[])
Foo() = Foo{Bar,Float64}(Bar[], Float64[])
julia> Foo()
Foo{Bar,Float64}(Bar[], Float64[])

julia> Foo{Int64}()
ERROR: TypeError: in Foo, in V, expected V<:AbstractBar, got Type{Int64}

What am I missing here?

1 Like

You can’t re-order type parameters.

You can’t do this because Foo{X} is an abstract type Foo{X,T}:

julia> Foo{Bar}
Foo{Bar,T} where T<:Real

So Foo{Int} will fail because your Foo type requires the first type parameter to be a subtype of AbstractBar.

2 Likes