调用使用 __LINE__ 构建的函数名

发布于 2024-11-18 15:59:21 字数 398 浏览 4 评论 0原文

假设,我从下面的代码构建了一个独特的函数体:

#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define UNIQUE static void TOKENPASTE2(Unique_, __LINE__)(void)

我如何调用这个函数?

宏定义取自: 使用 # 创建 C 宏# 和 __LINE__ (带有定位宏的标记串联)

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅黛梨妆こ 2024-11-25 15:59:21

不,你不能。因为你无法在运行时确定函数名称。 (即调用 Unique_22Unique_44。但是,您绝对可以调用 Unique<22>Unique<44> >)

所以你可以使用 template 解决方案。声明 Unique 如下:

template<unsigned int LINE> void Unique ();

#define 宏如下:

#define UNIQUE template<> Unique<__LINE__>() {}

我建议使用 __COUNTER__ 而不是 __LINE__ if你的编译器支持它。
[注意:这意味着在任何行中您只能调用 UNIQUE 一次,并且宏应该在全局或 namespace 范围内扩展(而不是在方法内部)。]

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).]

江湖彼岸 2024-11-25 15:59:21

将代码替换为您指出的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文