我有以下查询,可以看出,它们需要大量的复制/粘贴。
有一种快速而优雅的方法可以通过元编程来解决这个问题吗?
no matching function for call to 'QQmlListProperty<TTimingDriver>::QQmlListProperty(TTiming*, QList<TTimingDriver*>*, int (TTiming::*)(QQmlListProperty<TTimingDriver>*), TTimingDriver* (TTiming::*)(QQmlListProperty<TTimingDriver>*, int))'
return QQmlListProperty<TTimingDriver>(this, &m_drivers, &TTiming::count, &TTiming::driverAt);
答案 0 :(得分:1)
未经测试和丑陋,但我会说:
def days_of_week do
days = ~w(monday tuesday wednesday thursday friday saturday sunday)a
for {day, index} <- Enum.with_index(days) do
{day, quote do fragment("count(extract(dow FROM ?) = ? OR null)", c.inserted_at, unquote(index)) end}
end
end
defmacro by_day_of_week,
do: quote do: %{unquote_splicing(days_of_week)}
它产生代码:
"%{
monday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 0),
tuesday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 1),
wednesday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 2),
thursday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 3),
friday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 4),
saturday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 5),
sunday: fragment(\"count(extract(dow FROM ?) = ? OR null)\", c.inserted_at(), 6)
}"
因此与第二个。
答案 1 :(得分:0)
如果你真的想用宏做,你可能会这样做。
defmodule MapUtils do
defmacro spam(numbers) do
quote do
Enum.reduce(unquote(numbers), %{}, fn (elem, acc) ->
Map.put(acc, elem, elem)
end)
end
end
end
非常感谢Chris Wende