繁体   English   中英

julia调度参数抽象类型

[英]julia dispatch on parametric abstract type

考虑以下设置

abstract AbstractShape
type Shape_1 <: AbstractShape end
type Shape_2 <: AbstractShape end
type Shape_3 <: AbstractShape end

abstract AbstractElement{S<:AbstractShape}
type Element_1{S} <: AbstractElement{S} end
type Element_2{S} <: AbstractElement{S} end
#...
type Element_n{S} <: AbstractElement{S} end

我想检索每个具体元素类型的形状类型参数S,例如

shape(::Type{Element_1{Shape_3}}) = Shape_3

使用类似的东西

shape{S}(::Type{AbstractElement{S}}) = S

所以我不必为每种元素类型编写shape函数。

这有可能,我该怎么做? (谢谢你的帮助!)

我不会在0.5中建议Gnimuc的解决方法,因为如果具体的Element_n并非都具有相同类型,它将会失败; 即如果Element_4{N,S} <: AbstractElement{S}

相反,更好的解决方法是eltype在0.5中使用的技巧; 那是

shape{S<:AbstractShape}(::Type{AbstractElement{S}}) = S
shape{T<:AbstractElement}(::Type{T}) = shape(supertype(T))

当然,在0.6上,您可以简单地编写调度:

(shape(::Type{T}) where T <: AbstractElement{S} where S <: AbstractShape) = S

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM