In Julia, can a macro access the inferred type of its arguments?

时间:2015-05-24 21:57:59

标签: julia

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

2 个答案:

答案 0 :(得分:8)

宏不能这样做,但生成的函数可以。

点击此处的文档:http://julia.readthedocs.org/en/latest/manual/metaprogramming/#generated-functions

答案 1 :(得分:4)

除了spencerlyon2的答案之外,另一个选择是生成显式分支:

macro report_int(x)
    :(isa(x,Int64) ? "it's an int" : "not an int")
end

如果在函数内部使用@report_int(x),并且可以推断出x的类型,则JIT将能够优化掉死分支({{3}使用此方法在标准库中。)