为了实例化类似x = MyType{Int}()
的类型
我可以定义一个内部构造函数。
immutable MyType{T}
x::Vector{T}
MyType() = new(T[])
end
使用外部构造函数是否有可能实现相同的目标?
这可以使用以下语法完成:
(::Type{MyType{T}}){T}() = MyType{T}(T[])
第一组括号中的内容描述了被调用的对象。::T
的意思是"T类型的",所以这是一个用于调用Type{MyType{T}}
类型对象的定义,这意味着对象MyType{T}
本身。下一个{T}
意味着T
是该定义的参数,并且它的值必须可用才能调用该定义。所以MyType{Int}
匹配,但MyType
不匹配。从那时起,语法应该很熟悉。
这种语法肯定有点复杂和不直观,我们希望在未来的语言版本中改进它,希望是v0.6。
我可能错了,但如果你不能构建这样的无参数函数:
julia> f{T}() = show(T)
WARNING: static parameter T does not occur in signature for f at none:1.
The method will not be callable.
f (generic function with 1 method)
因此你将无法做到这一点:
julia> immutable MyType{T}
x::Vector{T}
end
julia> MyType{T}() = MyType{T}(T[])
WARNING: static parameter T does not occur in signature for call at none:1.
The method will not be callable.
MyType{T}
julia> x = MyType{Int}()
ERROR: MethodError: `convert` has no method matching convert(::Type{MyType{Int64}})
...
每个外部构造函数也是一个函数。
你可以说
f(T::Type) = show(T)
以及
MyType(T::Type) = MyType(T[])
但julia需要查看通话中的类型才能知道你想要哪个。