Reputation: 1242
In Julia, is there a way to write a macro that branches based on the (compile-time) type of its arguments, at least for arguments whose types can be inferred at compile time? Like, in the example below, I made up a function named code_type
that returns the compile-time type of x
. Is there any function like that, or any way to produce this kind of behavior? (Or do macros get expanded before types are inferred, such that this kind of thing is impossible.)
macro report_int(x)
code_type(x) == Int64 ? "it's an int" : "not an int"
end
Upvotes: 7
Views: 567
Reputation: 9676
Macros cannot do this, but generated functions can.
Check out the docs here: https://docs.julialang.org/en/v1/manual/metaprogramming/#Generated-functions-1
Upvotes: 10
Reputation: 7864
In addition to spencerlyon2's answer, another option is to just generate explicit branches:
macro report_int(x)
:(isa(x,Int64) ? "it's an int" : "not an int")
end
If @report_int(x)
is used inside a function, and the type of x
can be inferred, then the JIT will be able to optimise away the dead branch (this approach is used by the @evalpoly
macro in the standard library).
Upvotes: 7