带有“占位符”的宏价值

发布于 2024-11-09 01:47:42 字数 620 浏览 7 评论 0原文

我正在使用一个包含一组预处理器库的库。其中之一是 FOR_EACH 样式宏,它迭代 __VA_ARGS__ 并为每个参数调用用户提供的宏。用户提供的宏的调用方式如下:SOME_MACRO(current_arg)

但是,问题是它仅适用于采用单个参数的用户提供的宏。我正在尝试做一些特殊的事情,其中​​涉及结构的名称和结构中的每个字段。问题是,这需要宏的两个参数。

由于我正在使用的库仅接受一元宏,因此是否有某种方法可以将附加参数“绑定”到我的宏?

截至目前,我必须在宏中对结构的名称进行硬编码。因此,如果我正在使用的 struct 名为 Foo,我不得不说:

#define MY_MACRO(FIELD) /* do something with &Foo::FIELD */

是否可以通过某种方式“绑定”第二个 STRUCT > 宏的参数,也许有一些进一步的间接,这样当库调用我的宏时,它就可以扩展为:

#define MY_MACRO(FIELD) /* do something with &STRUCT::FIELD */

I'm working with a library that includes a set of preprocessor libraries. One of them is a FOR_EACH style macro which iterates over a __VA_ARGS__ and calls a user-provided macro for each argument. The user provided macro is called like: SOME_MACRO(current_arg)

However, the problem is that it only works with user-provided macros that take a single argument. I'm trying to do something special which involves both the name of a struct and each field in the struct. The problem is, this requires two arguments to the macro.

Since the library I'm working with only accepts a unary macro, is there some way to "bind" an additional argument to my macro?

As of now, I have to hardcode the name of the struct in my macro. So, if the struct I'm working with is named Foo, I have to say:

#define MY_MACRO(FIELD) /* do something with &Foo::FIELD */

Is there someway I could "bind" a second STRUCT argument to the macro, perhaps with some further indirection, so that when the library invokes my macro it would be able to expand as:

#define MY_MACRO(FIELD) /* do something with &STRUCT::FIELD */

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

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

评论(1

依 靠 2024-11-16 01:47:42

是的。您可以使用以下技术。

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

下面的测试代码中的用法:

struct foo { static int f() { return 0; } };
struct STRUCT { static int f() { return 1; } };

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

int main ()
{
  int i = MY_MACRO((STRUCT,f)); // see here braces inside braces
}

上面的代码扩展为,

int main ()
{
  int i = STRUCT::f();
}

Yes. You can use following technique.

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

Usage in the below test code:

struct foo { static int f() { return 0; } };
struct STRUCT { static int f() { return 1; } };

#define MY_MACRO(FIELD) EXPAND FIELD
#define EXPAND(X, FIELD) X::FIELD()

int main ()
{
  int i = MY_MACRO((STRUCT,f)); // see here braces inside braces
}

Above code is expanded to,

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