在 v0.6 的 Julia 手册中,我发现以下内容:
abstract type Pointy{T} end
struct Point{T} <: Pointy{T}
x::T
y::T
end
Run Code Online (Sandbox Code Playgroud)
这工作得很好,我认为以下也应该:
abstract type Foo{V, F} end
struct Bar{V, F} <: Foo{V, F}
x::V{F}
end
Run Code Online (Sandbox Code Playgroud)
然而,的定义Bar给出了以下错误
ERROR: TypeError: Type{...} expression: expected UnionAll, got TypeVar
Run Code Online (Sandbox Code Playgroud)
出了什么问题,我怎样才能实现我真正想要的,即指定V<:AbstractVector和F<:AbstractFloat?
尝试这个:
julia> abstract type Foo{T} end
julia> struct Bar{T<:AbstractFloat,V<:AbstractVector{T}} <: Foo{T}
x::V
end
julia> Bar{T}(v::AbstractVector{T}) = Bar{T,typeof(v)}(v) # constructor
Bar
julia> Bar(rand(3))
Bar{Float64,Array{Float64,1}}([0.387467, 0.535419, 0.240748])
julia> Bar(rand(Int, 3))
ERROR: TypeError: Bar: in T, expected T<:AbstractFloat, got Type{Int64}
Stacktrace:
[1] Bar(::Array{Int64,1}) at ./REPL[4]:1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3793 次 |
| 最近记录: |