如何在 Julia 中为抽象类型的所有参数子类型定义方法?

jul*_*ohm 1 julia

假设我有一个抽象基类:

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函数似乎不包含参数类型TV我正在尝试查询,是否有一个干净的解决方案?

for C in subtypes(B)
    # how to define result_type for C?
end
Run Code Online (Sandbox Code Playgroud)

Chr*_*kas 5

只需将类型参数添加到抽象类型即可。

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)