Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Created March 22, 2013 22:51
Show Gist options
  • Save johnmyleswhite/5225361 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/5225361 to your computer and use it in GitHub Desktop.
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
Copy link

Looks good to me!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment