Calling a function name built with __LINE__
Suppose, I have built an unique function body from b开发者_如何学Pythonelow code:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define UNIQUE static void TOKENPASTE2(Unique_, __LINE__)(void)
How can I call this function ?
Macro definition taken from: Creating C macro with ## and __LINE__ (token concatenation with positioning macro).
No. You cannot. Because you cannot determine a function name at runtime. (i.e. either to call Unique_22
or Unique_44
. However you can definitely call Unique<22>
or Unique<44>
)
So you can use template
solution instead. Declare Unique
as below:
template<unsigned int LINE> void Unique ();
And #define
the macro like this:
#define UNIQUE template<> Unique<__LINE__>() {}
I advice to use __COUNTER__
instead of __LINE__
if your compiler supports it.
[Note: which means that in any line you can call the UNIQUE
only once and also the macro should be expanded in global or namespace
scope (not inside a method).]
After replacing the code with the one given in the answer to the SO question you pointed so that it works, ... you can't call this function directly since you can't know for sure its name, that will change if the code change. I have no clue about how this can be useful in code (maybe scanning an object for symbol like Unique_[0-9]+
? Anyway, it would be an indirect use, in code, as said, you can't use it reliably.
精彩评论