How to do literal dispatch?

I’d like to make a function dispatch on literal inputs, like how Base.^ dispatches on literal_pow, but I have no idea how it works. A quick search suggests it’s done by the compiler which means that my goal is not possible.

I don’t think you can dispatch on constants but the compiler is getting pretty good at compiling functions with constant inputs.


literal_pow is a special case that happens during lowering, so you can’t do it yourself:

julia> Meta.@lower  1 ^ 2
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1 ─ %1 = ^
│   %2 = Core.apply_type(Base.Val, 2)
│   %3 = (%2)()
│   %4 = Base.literal_pow(%1, 1, %3)
└──      return %4

You can dispatch on “plain bits” values if you put them into a type parameter. See the docs for Val, etc."Value-types"