Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Dispatching on types with the same UnionAll (but you don't know the types beforehand).
using SimpleTraits, Test
abstract type A{T} end
struct B{T} <: A{T} end
struct C{T} <: A{T} end
abstract type D{T} <: A{T} end
struct E{T} <: D{T} end
struct F{T} <: D{T} end
sameunionall(::Type{X}, ::Type{Y}) where {X<:A, Y<:A} = !isabstracttype(typejoin(X, Y))
@traitdef SameUnionAll{X, Y}
@traitimpl SameUnionAll{X, Y} <- sameunionall(X, Y)
@traitfn f(::X, ::Y) where {X<:A, Y<:A; SameUnionAll{X, Y}} = "yo"
@traitfn f(::X, ::Y) where {X<:A, Y<:A; !SameUnionAll{X, Y}} = "nah"
x = B{Int64}()
y = B{Float32}()
z = C{Int64}()
@test f(x, y) == "yo"
@test f(x, z) == "nah"
@test f(y, z) == "nah"
# added later by a user
struct G{T} <: D{T} end
@test f(G{Int16}(), x) == "nah"
@test f(G{Int16}(), G{BigFloat}()) == "yo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment