假设我有一个抽象基类:
abstract type B end
Run Code Online (Sandbox Code Playgroud)
以及许多具体的子类型:
struct C1{T,V} <: B end
struct C2{T,V} <: B end
...
Run Code Online (Sandbox Code Playgroud)
如何以优雅的方式为所有子类型定义一个方法?
result_type(::C1{T,V}) = T
result_type(::C2{T,V}) = T
...
Run Code Online (Sandbox Code Playgroud)
该subtypes
函数似乎不包含参数类型T
,V
我正在尝试查询,是否有一个干净的解决方案?
for C in subtypes(B)
# how to define result_type for C?
end
Run Code Online (Sandbox Code Playgroud)
只需将类型参数添加到抽象类型即可。
abstract type B{T,V} end
struct C1{T,V} <: B{T,V} end
struct C2{T,V} <: B{T,V} end
result_type(::B{T,V}) where {T,V} = T
Run Code Online (Sandbox Code Playgroud)