julia 参数构造函数

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

假设我写了以下 julia 结构:

struct Foo{S, T}
    v::Vector{S}
    t::T
end

如果我希望

v
默认为空,我可以编写一个自定义构造函数

Foo{Int, String}(t::String) = Foo{Int, String}([], t)

那么下面两行是等价的:

f = Foo{Int, String}([], "hi")
f = Foo{Int, String}("hi")

但我只能对

Foo{Int, String}
对象使用方便的自定义构造函数,而不能使用任何其他类型的
Foo
。如何为
Foo{S, T}
编写一个参数构造函数,它只接受
t
的值并将
v
初始化为空?

templates constructor julia
1个回答
0
投票

@DNF 评论之外的其他有趣选项:

@kwdef struct Foo{S, T}
    v::Vector{S}=S[]
    t::T
end
Foo{S}(t::T) where {S, T} = Foo(S[], t)

比你能做的:

julia> Foo{Int,Float64}(t=5.0)
Foo{Int64, Float64}(Int64[], 5.0)

julia> Foo{Int}(5.0)
Foo{Int64, Float64}(Int64[], 5.0)
© www.soinside.com 2019 - 2024. All rights reserved.