简体   繁体   English

为什么不能打印出宏创建的结构的所有成员名称?

[英]Why can't I print out all of the member names of my macro-created struct?

I'm a bit of a noob when it comes to using macros, but I am running into a problem that I can't explain. 在使用宏时,我有些菜鸟,但是遇到了我无法解释的问题。

I have used macros to generate the BlockA struct like this: 我已经使用宏来生成如下所示的BlockA结构:

#define TO_STRUCT(structname, type, member, size) type member size;
#define MEMBER_COUNT(structname, type, member, size) +1
#define MEMBER_NAME(structname, type, member, size)  #member,

#define BLOCK_STRUCT_MEMBERS(p)\
    p(BlockA, RegTypeA, regA, [5])\
    p(BlockA, RegTypeB, regB, )\

 struct BlockA {
    BLOCK_STRUCT_MEMBERS(TO_STRUCT)
    int addr;
    BlockA(int address);
};

And then, I have printed out the count of how many members were put into the struct using the macros: 然后,我打印出了使用宏将多少个成员放入结构的计数:

std::cout << BLOCK_STRUCT_MEMBERS(MEMBER_COUNT);

This prints out the correct response: 2, and if I did the same with the second member commented out when I define it in BLOCK_STRUCT_MEMBERS, it prints 1, which makes sense. 这将打印出正确的响应:2,并且如果我在BLOCK_STRUCT_MEMBERS中定义第二个成员时也将其注释掉,则将其打印为1,这很有意义。 So that seems to be working. 因此,这似乎可行。 But if I try to print the names of the members using almost exactly the same method, like this, it only prints the name of the first member: 但是,如果我尝试使用几乎完全相同的方法来打印成员的名称,像这样,它只会打印第一个成员的名称:

std::cout << BLOCK_STRUCT_MEMBERS(MEMBER_NAME)

It also complains that it expected an expression when I try to put a semicolon after it, like I did when I printed the count. 它还抱怨说,当我尝试在其后加上分号时,它期望一个表达式,就像我打印计数时那样。 Why is this happening? 为什么会这样呢?

I think it's the comma after "#member" in your "MEMBER_NAME" macro. 我认为这是您的“ MEMBER_NAME”宏中“ #member”之后的逗号。 If I delete it it works fine for me. 如果我删除它,对我来说很好。

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

相关问题 为什么不能定义这些宏名称? - Why can't I define these macro names? 为什么我不能使用我的无序 map 从 boost 图形库中打印出这个顶点的名称 - Why can't I use my unordered map to print out a name for this vertex from boost graph library 是否有任何方法可以打印结构的所有成员变量? - Is there any method can print all member variable of a struct? 为什么我不能打印出我的字符串数组c ++? - Why can't I print out my string array c++? 为什么我不能调用我的结构信号量方法? - Why can't I call my struct Semaphore methods? 为什么我可以通过SubBase类的公开引入的方法打印出Base类的私有继承成员? - Why can I print out a privately inherited member of the Base class through a publicly inhterited method of the SubBase class? 为什么我不能打印向量中的元素? - Why can't I print the elements in my vector? 似乎无法打印出我的字符串 - Can't seem to print my string out 为什么“具有const成员的结构”类型的指针不能指向“具有非const成员的结构”? - Why can't a pointer of a “struct with const member” type point to a “struct with non-const member”? 任何可以导出 pybind11 结构的所有成员变量的 C++ 宏 - Any C++ macro that can export all member variables of a struct for pybind11
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM