调用使用 __LINE__ 构建的函数名
假设,我从下面的代码构建了一个独特的函数体:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define UNIQUE static void TOKENPASTE2(Unique_, __LINE__)(void)
我如何调用这个函数?
Suppose, I have built an unique function body from below 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,你不能。因为你无法在运行时确定函数名称。 (即调用
Unique_22
或Unique_44
。但是,您绝对可以调用Unique<22>
或Unique<44>
>)所以你可以使用
template
解决方案。声明Unique
如下:#define
宏如下:我建议使用
__COUNTER__
而不是__LINE__
if你的编译器支持它。[注意:这意味着在任何行中您只能调用
UNIQUE
一次,并且宏应该在全局或namespace
范围内扩展(而不是在方法内部)。]No. You cannot. Because you cannot determine a function name at runtime. (i.e. either to call
Unique_22
orUnique_44
. However you can definitely callUnique<22>
orUnique<44>
)So you can use
template
solution instead. DeclareUnique
as below:And
#define
the macro like this: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 ornamespace
scope (not inside a method).]将代码替换为您指出的 SO 问题的答案中给出的代码以便它可以工作后,...您不能直接调用此函数,因为您无法确定它的名称,如果代码改变。我不知道这在代码中有何用处(也许扫描对象中是否有像
Unique_[0-9]+
这样的符号?无论如何,这将是代码中的间接使用,如上所述,你无法可靠地使用它。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.