如何在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)
谢谢你,先生!