Created
March 22, 2013 22:51
-
-
Save johnmyleswhite/5225361 to your computer and use it in GitHub Desktop.
Delegation macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################################################## | |
# | |
# 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good to me!