Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delegation macro
##############################################################################
#
# A macro for doing delegation
#
# This macro call
#
# @delegate MyContainer.elems [:size, :length, :ndims, :endof]
#
# produces this block of expressions
#
# size(a::MyContainer) = size(a.elems)
# length(a::MyContainer) = length(a.elems)
# ndims(a::MyContainer) = ndims(a.elems)
# endof(a::MyContainer) = endof(a.elems)
#
##############################################################################
macro delegate(source, targets)
typename = esc(source.args[1])
fieldname = esc(Expr(:quote, source.args[2].args[1]))
funcnames = targets.args
n = length(funcnames)
result = quote begin end end
for i in 1:n
funcname = esc(funcnames[i])
f = quote
($funcname)(a::($typename), args...) = ($funcname)(a.($fieldname), args...)
end
push!(result.args[2].args, f)
end
return result
end
##############################################################################
#
# Example
#
##############################################################################
importall Base
type MyContainer
elems::Array
end
@delegate MyContainer.elems [size, length];
x = MyContainer([1, 2, 3, 4])
size(x)
length(x)
@kmsquire

This comment has been minimized.

Copy link

kmsquire commented Mar 23, 2013

Looks good to me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.