如何使用宏在C ++中生成随机变量名? [英] How to generate random variable names in C++ using macros?

查看:1724
本文介绍了如何使用宏在C ++中生成随机变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中创建一个宏,声明一个变量并为其赋予一些值。根据宏的使用方式,宏的第二次出现可以覆盖第一个变量的值。例如:

I'm creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the value of the first variable. For instance:

#define MY_MACRO int my_variable_[random-number-here] = getCurrentTime();

使用它的另一个动机是避免选择变量的特定名称,作为开发人员使用宏最终选择的名称。

The other motivation to use that is to avoid selecting certain name to the variable so that it be the same as a name eventually chosen by the developer using the macro.

是否有一种方法可以在C ++中的宏中生成随机变量名称?

Is there a way to generate random variable names inside a macro in C++?

- 编辑 -

我的意思是唯一的,但也可以随机,一旦我可以在一个块中使用我的宏两次,在这种情况下,例如:

I mean unique but also random once I can use my macro twice in a block and in this case it will generate something like:

int unique_variable_name;
...
int unique_variable_name;

在这种情况下,两个变量名必须是随机生成的。

In this case, to be unique both variable names have to be random generated.

推荐答案

将M4添加到构建流程中?这种宏语言具有一些有状态的功能,并且可以成功地与CPP宏混合。这可能不是在C环境中生成唯一名称的标准方法,但我已经能够以这种方式成功使用它。

Add M4 to your build flow? This macro language has some stateful capabilities, and can successfully be intermingled with CPP macros. This is probably not a standard way to generate unique names in a C environment, though I've been able to sucessfully use it in such a manner.

您可能不需要不想随机,BTW,根据你提出你的问题的方式。

You probably do not not want random, BTW, based on the way you posed your question. You want unique.

您可以使用 __ FILE __ __LINE __ 在宏展开,以获得你的唯一性,你似乎要去...那些元数据在源文件上下文中定义,所以要小心,以确保你得到你正在寻找例如,同一行上的多个宏的危险)。

You could use __FILE__ and __LINE__ in the macro expansion to get you the uniqueness you seem to be going for... those metavariables get defined within the source file context, so be careful to make sure you get what you are looking for (e.g., perils of more than one macro on the same line).

这篇关于如何使用宏在C ++中生成随机变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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