Adding methods with metaprogramming

I have a couple of types defined like this:

struct Foo
    foo
end

struct Bar
    foo::Foo
    bar
    baz
end

Then I have a bunch of functions defined for Foo, with additional methods for Bar that just pass through the foo field:

func1(f::Foo, x) = x + f.foo
func1(b::Bar, x) = func1(b.foo, x)

func2(f::Foo, x, y) = x*y - f.foo
func2(b::Bar, x, y) = func2(b.foo, x, y)

Is there some way to generate the Bar methods automatically, using a macro or something?

Yes, see the metaprogramming docs around the example

for op = (:sin, :cos, :tan, :log, :exp)
    @eval Base.$op(a::MyNumber) = MyNumber($op(a.x))
end

This is a very common pattern, you can find many similar ones in the Julia source code and packages.

4 Likes