简体   繁体   English

C ++宏-传递字符串并用作变量名

[英]C++ Macro - pass string and use as a variable name

So i'm working on a small hobby project which i have implemented a very basic reflection of enums. 因此,我正在进行一个小型的业余项目,该项目已经实现了枚举的非常基本的体现。 I have come across an issue which i'm struggling to find a solution. 我遇到了一个我正在努力寻找解决方案的问题。

This would be an ideal call which i'm looking for 这是我正在寻找的理想电话

    Reflect_Value("TestStringName", "StringValue")

the first parameter is a string which is intended to be appended onto a variable name and the second to be the actual string value 第一个参数是一个字符串,打算附加到变量名上,第二个参数是实际的字符串值

#define Reflect_Value(name,t)   \
namespace Reflection {          \
static ReflectedObject object_##name = ReflectedObject(name,t); }\

now the macro would then take that first parameter and be used as object_TestStringName but when i pass the string in the code evaluates to object_"TestStringName" which doesn't compile. 现在,宏将采用第一个参数,并用作object_TestStringName,但是当我在代码中传递字符串时,其结果将评估为无法编译的object_“ TestStringName”。

What am i doing wrong here or can anyone provide any solutions to how i could get this functionality please. 我在这里做错了什么,或者任何人都可以为我提供该功能的方法提供任何解决方案。 its important to have the name be something i guess recognisable and also unique so i can reflect many objects 重要的是要使这个名称成为我猜可以识别的名称,并且也要唯一,这样我才能反映出许多对象

Thanks 谢谢

I think you can do what you want with the stringification operator # : 我认为您可以使用字符串化运算符#进行所需的操作:

#define Reflect_Value(name,t)   \
namespace Reflection {          \
static ReflectedObject object_##name = ReflectedObject( #name, #t ); }\

You'd then call the macro with unquoted arguments: 然后,您可以使用不带引号的参数调用宏:

Reflect_Value(TestStringName, StringValue)

Don't pass a string, but stringize it: 不要传递字符串,而是将其字符串化:

#define stringize(name) #name
#define Reflect_Value(name,t)   \
namespace Reflection {          \
static ReflectedObject object_##name = ReflectedObject(stringize (name),t); }

Then: 然后:

Reflect_Value(TestStringName, "StringValue")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM