Erlang macros with different arity
For my logging I wanted the ability to macro out the statements at compile time, so -define to the rescue!
For my compiler flags I'm compiling with erlc -DFOO, is there a way for -ifdef to determine the difference between FOO = ok, FOO/0, and FOO/1?
-module(foo).
-define(FOO, ok).
-define(FOO(X), io:format("~p开发者_如何学Python~n", [X])).
-export([test_x/1]).
%% i want this to be true iff FOO = ok, not if ?FOO/1 exists
-ifdef(FOO).
test_x(X) ->
?FOO(":) " ++ X).
-else.
test_x(X) ->
?FOO(":( " ++ X).
-endif.
I had better write a fuller reply.
No, there is no way to test the actual macro definition, you can only test if a macro with that name has been defined. And you can only test on the macro name, not on alternative macro definitions with different arities. This is relic from the past, before R13B, when you could only have one macro definition per name. The new one more closely mimics functions in a module.
The "standard" way of doing it is to use some flag macro to determine which set of macros/functions to use. For example:
-ifdef(DEBUG).
-define(DEBUG_PRINT(X), <... something long here ...>).
foo(X) -> <... debuggy stuff here ...>.
-else
-define(DEBUG_PRINT(X), ok).
foo(X) -> <... normal stuff here ...>.
-endif.
精彩评论