如何定义参数类型而不是参数类型?

colinfang

假设我有类型

immutable X{T}
    a::T
end

immutable Y{T}
    a::T
end

我想做类似的事情

type A{T, U}
    x::U{T}
    y::T
end

这样实例可以是A(X(a), a)A(Y(a), a)

它不起作用 LoadError: TypeError: Type{...} expression: expected Type{T}, got TypeVar

正确的方法是什么?

尼穆克

如错误所示,UTypeVar,不是Type答案是制作U一个真实的类型:

julia> abstract U{T}

julia> immutable X{T} <: U{T}
           a::T
       end

julia> immutable Y{T} <: U{T}
           a::T
       end

julia> type A{T}
           x::U{T}
           y::T
       end

julia> A(X(1),1)
A{Int64}(X{Int64}(1),1)

julia> A(X(1),1.)
ERROR: MethodError: no method matching A{T}(::X{Int64}, ::Float64)
Closest candidates are:
  A{T}{T}(::U{T}, ::T) at REPL[4]:2
  A{T}{T}(::Any) at sysimg.jl:53

julia> A(Y(1),1)
A{Int64}(Y{Int64}(1),1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章