Macros Julia中类型字段上的笛卡尔宏

Macros Julia中类型字段上的笛卡尔宏,macros,julia,Macros,Julia,Base.Cartesian模块提供@nref宏: using Base.Cartesian i_1, i_2 = 1, 1 A = rand(3,3) @nref 2 A i 这将返回A[1,1]。但是,@nref不适用于(自定义)类型的字段: 这将导致一个错误: ERROR: MethodError: `_nref` has no method matching _nref(::Int64, ::Expr, ::Symbol) Closest candidates are: _nref

Base.Cartesian
模块提供
@nref
宏:

using Base.Cartesian
i_1, i_2 = 1, 1
A = rand(3,3)
@nref 2 A i
这将返回
A[1,1]
。但是,
@nref
不适用于(自定义)类型的字段:

这将导致一个错误:

ERROR: MethodError: `_nref` has no method matching _nref(::Int64, ::Expr, ::Symbol)
Closest candidates are:
  _nref(::Int64, ::Symbol, ::Any)
这个错误似乎是合理的,因为
foo.bar
实际上是表达式
getfield(foo,bar)
。 将
@nref
包装在函数中并传递
foo.bar
起作用:

function baz(A)
i_1, i_2 = 1, 1
@nref 2 A i
end

baz(foo.bar)

但是有没有办法让
@nref 2 foo.bar i
工作呢?

如果你把
foo.bar
赋值给一个变量,比如
TT=foo.bar
,那么
@nref 2 TT i
工作。这基本上是免费的,因为没有复制,在函数内部优化使
TT
foo.bar
相同

这是我担心的复制
TT=foo.bar
,但是
@time
同意您关于优化器的看法。谢谢!我很乐意将问题标记为已回答,但只需一句评论就可以了吗?
function baz(A)
i_1, i_2 = 1, 1
@nref 2 A i
end

baz(foo.bar)