是否知道是否可以在一行中使用多个宏?例如,
@devec, @inbounds [expr]
宏是在编译时用于生成表达式的函数的类似物。就像函数将参数值的元组映射到返回值一样,宏将参数表达式的元组映射到返回的表达式。使用以下通用语法调用宏:
@name expr1 expr2 ...
@name(expr1, expr2, ...)
这是一个使用两个众所周知的宏的示例(尽管有点荒谬):
# This is an assert construct very similar to what you'd find in a language like
# C, C++, or Python. (This is slightly modified from the example shown in docs)
macro assert(ex)
return :($ex ? println("Assertion passed") # To show us that `@assert` worked
: error("Assertion failed: ", $(string(ex))))
end
# This does exactly what you expect to: time the execution of a piece of code
macro timeit(ex)
quote
local t0 = time()
local val = $ex
local t1 = time()
println("elapsed time: ", t1-t0, " seconds")
val
end
end
但是,请分别注意以下两个成功的宏调用(即,不要抛出任何错误):
@assert factorial(5)>=0
@timeit factorial(5)
并且,现在一起:
@timeit @assert factorial(5)>=0
因为最右边的宏没有引发错误,所以上面的行将返回factorial(5)
执行和断言所花费的总时间。
但是,需要注意的重要一点是,当其中一个宏发生故障时,调用堆栈中其他宏的执行当然会终止(应该如此):
# This will throw an error (because we explicitly stated that @assert should
# do so. As such, the rest of the code did not execute.
@timeit @assert factorial(5)<0
再次,这是一个愚蠢的示例,但说明了以上几点并解决了您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句