在类名称列表上迭代预处理器宏 [英] Iterate a preprocessor macro on a list of class names

查看:71
本文介绍了在类名称列表上迭代预处理器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在类名列表上运行宏,以避免复制/粘贴错误和麻烦.

I would like to run macros on a list of class names to avoid copy/pasting errors and hassle.

想象一下,作为一个简单的示例,SDK中的每个类在使用前都需要调用静态分配方法.因此,每次添加新类时,都必须在初始化时手动添加以下行:

Imagine, as a simple example, that every class in my SDK needs to call a static allocation method before it is used. So, every time I add a new class, I have to manually add the following line at initialization:

MyNewClass::allocate();

我还需要对初始化和销毁​​做同样的事情.

And I also need to do the same for initialization and destruction.

因此,我想知道是否有一种方法可以在某个地方编写所有类名的列表,然后定义一个宏以为列表中的每个类调用相应的方法,而不是每次都手动执行此操作.符合以下条件的

So, instead of doing this manually every time, I was wondering if there was a way to write a list of all my class names somewhere, then define a macro to call the corresponding methods for each class in the list. Something in the lines of:

#define ALLOCATE( TheClass ) TheClass ## ::allocate();

但我不只是传递TheClass作为参数,而是传递一个我的类的列表.因此,致电:

But instead of just passing TheClass as an argument, I'd like to pass a list of my classes. So by calling:

ALLOCATE_ALL( ClassA, ClassB, ClassC )

它将扩展为:

ClassA::allocate();
ClassB::allocate();
ClassC::allocate();

最终,我希望能够定义一个类列表并在其上迭代多个宏.符合以下条件的

Ultimately, I would like to be able to define a class list and have multiple macros iterate over it. Something in the lines of:

ALLOCATE_ALL( MyClassList )
INIT_ALL( MyClassList )
DESTROY_ALL( MyClassList )

我已经研究了可变参数宏,但是,如果我正确地理解了这个概念,则必须定义与最终参数个数一样多的宏.就我而言,那简直是行不通的.

I've already taken a look at variadic macros but, if I understand the concept correctly, you have to define as many macros as the final number of arguments; and that is simply not viable in my case.

这有可能吗?

感谢您的帮助和/或反馈.

Thanks for any help and/or feedback.

推荐答案

如果对一个类列表感到满意,可以使用以下技巧:

If you are satisfied with having one list of classes, you can use the following trick:

#define MY_CLASSES X(ClassA) X(ClassB) X(ClassC)

然后您可以执行以下操作:

Then you can do something like:

#define X(a) a::allocate();
MY_CLASSES
#undef X

要执行其他操作,您可以执行以下操作:

To do something else, you can do:

#define X(a) a::init();
MY_CLASSES
#undef X

这篇关于在类名称列表上迭代预处理器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆