Tell the compiler the return type of function chosen at runtime

You can use FunctionWrappers.jl:

import FunctionWrappers: FunctionWrapper

function fun(idx, a::Int, b::Int)
    funs = FunctionWrapper{Int64, Tuple{Int64, Int64}}[+, -]
    return funs[idx](a, b)
end

@code_warntype fun(1, 3, 5)

Not a lot of documentation available, but I think it’s used quite extensively across the Julia ecosystem. Hopefully someone else can fill any technical details.

3 Likes