是否可以在TypeVar
中释放DataType
以获得UnionAll
?
大图,我想做的是:
# this doesnt work
f(::Type{V{T}}, ::Type{S}) where {T,S,V<:AbstractVector} = V{S}
f(Vector{Int}, Char)
# Vector{Char}
我目前的解决方案是@eval f(::Type{$(V){T}}, S::Type)
手动创建类型V <: AbstractVector
的列表,但我希望有一个更直接的解决方案
答案 0 :(得分:0)
您可以尝试这种方法:
[2],[4],[6],[9]
现在:
function f(::Type{V}, ::Type{S}) where {V<:AbstractVector{T}, S} where T
s = Core.Compiler.unwrap_unionall(V.name.wrapper)
v = s.super
while v.name.wrapper != AbstractArray
v = v.super
end
loc = findfirst(==(v.parameters[1]), s.parameters)
V.name.wrapper{V.parameters[1:loc-1]...,S,V.parameters[loc+1:end]...}
end
请注意,您使用julia> f(Vector{Int}, Char)
Array{Char,1}
julia> f(UnitRange{Int}, Float64)
UnitRange{Float64}
julia> abstract type MyType1{A,B,C} <: AbstractVector{B} end
julia> struct MyType2{P,Q,R,S} <: MyType1{R,Q,S} end
julia> f(MyType2{Int, Int, Int, Int}, Char)
MyType2{Int64,Char,Int64,Int64}
的方法并不完全通用,并且无法处理@eval
的复杂自定义子类型(作为示例中的最后一个)。