【发布时间】:2023-03-30 10:05:01
【问题描述】:
作为一个人工示例,假设我有一个参数结构,其中T <: AbstractFloat
mutable struct Summary{T<:AbstractFloat}
count
sum::T
end
我想在T === Float16 时将count 字段输入为UInt16,在T === Float32 时输入为UInt32,在所有其他情况下输入为UInt64。
我目前的方法是为 count 字段使用联合类型 Union{UInt16, UInt32, UInt64}
module SummaryStats
export Summary, avg
const CounterType = Union{UInt16, UInt32, UInt64}
mutable struct Summary{T<:AbstractFloat}
count::CounterType
sum::T
# explicitly typed no-arg constructor
Summary{T}() where {T<:AbstractFloat} = new(_counter(T), zero(T))
end
# untyped no-arg constructor defaults to Float64
Summary() = Summary{Float64}()
function avg(summary::Summary{T})::T where {T <: AbstractFloat}
if summary.count > zero(_counter(typeof(T)))
summary.sum / summary.count
else
zero(T)
end
end
# internal helper functions, not exported
Base.@pure _counter(::Type{Float16})::UInt16 = UInt16(0)
Base.@pure _counter(::Type{Float32})::UInt32 = UInt32(0)
Base.@pure _counter(::DataType)::UInt64 = UInt64(0)
end # module
这似乎可行,但显然@code_warntype 对count 字段的联合类型不满意。
我想知道是否有可能根据上面列出的规则以某种方式计算出正确的具体类型?
【问题讨论】:
标签: julia