Last active
December 13, 2021 16:41
-
-
Save mcognetta/a468889c2ea53b49d080c6d764f3b6da to your computer and use it in GitHub Desktop.
Dispatching on types with the same UnionAll (but you don't know the types beforehand). https://mcognetta.github.io/post/dispatch_unionall
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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