请考虑以下结构:
struct MyType1{T}
data::T
end
可以用两种方式实例化:
println(MyType1(5)) # MyType1{Int64}(5)
println(MyType1{Int}(5)) # MyType1{Int64}(5)
当我定义与内部构造函数相似的东西时:
struct MyType2{T}
data::T
MyType2(x::T) where T = new{T}(x)
end
struct MyType3{T}
data::T
MyType3{T}(x::T) where T = new{T}(x)
end
我只能以一种方式实例化它们:
println(MyType2(5)) # MyType2{Int64}(5)
println(MyType2{Int}(5)) # MethodError
println(MyType3(5)) # MethodError
println(MyType3{Int}(5)) # MyType3{Int64}(5)
如何使内部构造函数中的类型说明可选(在上面的示例中,使MyType2
和MyType3
不会抛出MethodError
?]
julia版本1.4.1
只需提供一个额外的构造函数:
struct MyType4{T}
data::T
MyType4{T}(x::T) where T = new{T}(x)
end
MyType4(x::T) where T = MyType4{T}(x)
测试
julia> MyType4{Int}(5)
MyType4{Int64}(5)
julia> MyType4(5)
MyType4{Int64}(5)