【问题标题】:How to pass a macro-argument to an expression within the same macro?如何将宏参数传递给同一宏中的表达式?
【发布时间】:2021-12-09 17:03:44
【问题描述】:
macro myMacro(name,arg)
    :(struct $name
       $(esc(arg.args[1]))
       function $name(;$(esc(arg.args[1]))=arg.args[2].args[2])
         new($(esc(arg.args[1])))
       end
    end)
end

我正在尝试创建一个具有默认值的结构,该默认值将作为宏的第二个参数。我知道当我将arg.args[2].args[2] 定义为默认参数时,它会报错,因为arg.args[2].args[2] 没有在struct 中定义,但我不知道如何定义它。

宏应扩展为:

macroexpand(Main,:(@myMacro myM ((arg,(default=10)))))


:(struct myM
      arg
      function myM(; arg = 10)
          new(arg)
      end)

【问题讨论】:

    标签: macros julia metaprogramming default-constructor


    【解决方案1】:

    你很接近,只是几个问题:

    1. 这里不需要esc。通常,为了避免与宏调用范围内的变量发生冲突,宏返回表达式的局部变量由gensym 重命名,全局变量取自宏定义 的范围。 esc 为表达式撤消此操作,因此该表达式中的变量可以与宏调用范围混合。在您的情况下,您尝试 esc 的变量是 structfunction 的本地变量,无论如何都没有机会与宏调用范围混合。

    2. 您忘记插入 arg.args[2].args[2] 位。

    macro myMacro(name,arg)
        :(struct $name
           $(arg.args[1])
           function $name(; $(arg.args[1]) = $(arg.args[2].args[2]) )
             new( $(arg.args[1]) )
           end
        end)
    end
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      相关资源
      最近更新 更多