使用参数化抽象类型转换重载

问题描述 投票:0回答:0

我又在玩Structs,发现了一些东西,我不太明白。
第一个案例效果很好:

abstract type Point{T} end
struct Point2D{T <: Number} <: Point{T}
    x::T
    y::T
end

Base.convert(::Type{T}, t::Tuple{Vararg{S}}) where S where T <: Point{} = T{S}(t...)
# or better
Base.convert(::Type{T}, t::Tuple) where T <: Point{} = T(t...)

println(Point2D[(4, 6)])

避免在引入例如时进行任何后续子类型检查

Point3D
我想,我会这么做

abstract type Point{T <: Number} end
struct Point2D{T} <: Point{T}
    x::T
    y::T
end

但这打破了

convert
过载。我认为问题出在
T <: Point{}
中,其中检查
{}
的类型
{T <: Number}
,因此重载不是有效的方法。

  • 在第二种情况下我将如何重载转换,
    S
    会发挥作用吗?
  • 参数化抽象类型是否可取?
struct type-conversion julia
© www.soinside.com 2019 - 2024. All rights reserved.