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

查看:33
本文介绍了如何使用宏在 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.

顺便说一句,根据您提出问题的方式,您可能不想要随机.你想要独特.

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天全站免登陆