如何在 Julia 中正确调用参数构造函数?

Ngọ*_*yễn 4 julia

我想调用复合类型的构造函数,WeightedPool1D但我尝试了两者WeightedPool1D(mask)WeightedPool1D{Float64}(mask)但没有奏效。

谢谢!

朱莉娅版本:1.6.1

我的代码:

# creating composite type
struct WeightedPool1D{T}
    n::Int
    c::Int
    mask::Matrix{Bool}
    weight::Matrix{T}
    function WeightedPool1D(mask::Matrix{Bool}) where T
        c, n = size(mask)
        weight = randn(T, c, n) / n
        new{T}(n, c, mask, weight)
    end
end

# create argument
mask = zeros(Bool, 3, 3)
Run Code Online (Sandbox Code Playgroud)

调用w = WeightedPool1D(mask)给出错误

julia> w = WeightedPool1D(mask)
ERROR: UndefVarError: T not defined
Run Code Online (Sandbox Code Playgroud)

调用w = WeightedPool1D{Float64}(mask)给出错误

julia> w = WeightedPool1D{Float64}(mask)
ERROR: MethodError: no method matching WeightedPool1D{Float64}(::Matrix{Bool})
Run Code Online (Sandbox Code Playgroud)

fre*_*kre 5

这里的问题是内部构造函数。没有任何东西(从输入到构造函数)定义T应该是什么。

如果你想要一个默认值T,比如说Float64,你可以定义以下内部构造函数

struct WeightedPool1D{T}
    n::Int
    c::Int
    mask::Matrix{Bool}
    weight::Matrix{T}

    # General constructor for any T, call as WeightedPool1D{Float64}(...)
    function WeightedPool1D{T}(mask::Matrix{Bool}) where T
        c, n = size(mask)
        weight = randn(T, c, n) / n
        new{T}(n, c, mask, weight)
    end
   
    # Construtors that defines a default T, call as WeightedPool1D(...)
    function WeightedPool1D(mask::Matrix{Bool})
        return WeightedPool1D{Float64}(mask) # Calls the other constructor, now with T = Int
    end
end
Run Code Online (Sandbox Code Playgroud)

示例调用:

mask = zeros(Bool, 3, 3)

WeightedPool1D(mask)
WeightedPool1D{Float32}(mask)
Run Code Online (Sandbox Code Playgroud)