Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Julia中恰当地调用参数构造函数?_Julia - Fatal编程技术网

如何在Julia中恰当地调用参数构造函数?

如何在Julia中恰当地调用参数构造函数?,julia,Julia,我想调用复合类型的构造函数WeightedPool1D,但我尝试了WeightedPool1D(mask)和WeightedPool1D{Float64}(mask),但都没有成功 谢谢 Julia版本:1.6.1 我的代码: # creating composite type struct WeightedPool1D{T} n::Int c::Int mask::Matrix{Bool} weight::Matrix{T} function Weigh

我想调用复合类型的构造函数
WeightedPool1D
,但我尝试了
WeightedPool1D(mask)
WeightedPool1D{Float64}(mask)
,但都没有成功

谢谢

Julia版本: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)
调用
w=WeightedPool1D(mask)
会产生错误

julia> w = WeightedPool1D(mask)
ERROR: UndefVarError: T not defined
julia> w = WeightedPool1D{Float64}(mask)
ERROR: MethodError: no method matching WeightedPool1D{Float64}(::Matrix{Bool})
调用
w=WeightedPool1D{Float64}(mask)
会产生错误

julia> w = WeightedPool1D(mask)
ERROR: UndefVarError: T not defined
julia> w = WeightedPool1D{Float64}(mask)
ERROR: MethodError: no method matching WeightedPool1D{Float64}(::Matrix{Bool})

这里的问题是内部构造函数。没有任何东西(从输入到构造函数)定义
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
电话示例:

mask = zeros(Bool, 3, 3)

WeightedPool1D(mask)
WeightedPool1D{Float32}(mask)

谢谢你,先生!