[英]creating an abstract type as a wrapper for different functions
我正在嘗試創建一個abstract type
,它是一個超類(稱為Kernel
)幾個不同的函數,每個函數Kernel
的子類——即
abstract type Kernel end
struct ExponentialKernel <: Kernel
ExponentialKernel(rate::Number, x::Number) = exp(-1*rate*x)
end
struct GaussianKernel <: Kernel
GaussianKernel(sigma::Number, x::Number) = (1.0/(sigma*sqrt(2*pi))) * exp((-1*x^2)/(2*sigma^2)
end
...
等等。
當我使用上面的內容時,它的工作原理是當我調用ExpKernel(a,b)
時我得到了正確的值,但是當我嘗試將這些 kernel 對象傳遞給不同的構造函數時,比如
mutable struct Model
kernel::T where {T <: Kernel}
Model(kernel) = new(kernel)
end
但是當我嘗試調用Model(ExpKernel)
時出現錯誤
ERROR: MethodError: Cannot `convert` an object of type Type{ExpKernel} to an object of type Kernel
我在這里缺少關於類型的東西嗎?
這是你想要的?
julia> mutable struct Model
kernel::DataType
Model(k::Type{<:Kernel}) =
isconcretetype(k) ? new(k) : throw(ArgumentError("concrete type required"))
end
julia> Model(GaussianKernel)
Model(GaussianKernel)
julia> Model(1)
ERROR: MethodError: no method matching Model(::Int64)
Closest candidates are:
Model(::Type{var"#s1"} where var"#s1"<:Kernel) at REPL[4]:4
Stacktrace:
[1] top-level scope at REPL[6]:1
julia> Model(Kernel)
ERROR: ArgumentError: concrete type required
Stacktrace:
[1] Model(::Type{Kernel}) at .\REPL[4]:4
[2] top-level scope at REPL[7]:1
但是請注意,這不是 Julia 中的典型設計模式 - 通常您會使用https://docs.julialang.org/en/v1/manual/methods/#Function-like-objects-1模式來實現此類功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.