如果我有抽象的Component并想要一个任何子类型的向量,我该如何指定Vector的类型参数?这个天真的片段不起作用:
type Position<:Component
x::Real
y::Real
end
v = Vector{Type{Component}}
push!(v, Position)
ERROR: MethodError: `push!` has no method matching push (::Type{Array{Type{Component},1}}, ::Type{Position})
Closest candidates are:
push!(::Any, ::Any, ::Any)
push!(::Any, ::Any, ::Any, ::Any...)
push!(::Array{Any,1}, ::ANY)
最佳答案 当您遇到可以使用类型而不是任何子类型的情况时,通常可以通过在正确的位置引入类型参数来实现.以下似乎有效:
abstract Component
type Position<:Component
x::Real
y::Real
end
typealias ComponentType{T<:Component} Type{T}
v = Vector{ComponentType}()
push!(v, Position)
请注意,我们通过使用带有typealias结构的type参数创建了Component的任何子类型所属的新类型ComponentType(包括Component本身).
现在,在实践中我不确定你是否通过这样做获得了很多,而不仅仅是让v = Vector();我不认为额外的类型信息会允许Julia编译器在这种情况下执行任何特定的优化.