简体   繁体   中英

Iterating a struct in C++

I'm having some trouble iterating over a struct.

The struct can be defined differently, depending on the compiler flags. I want to set all the struct members to 0. I don't know how many members there are, but they are all guaranteed to be numbers (int, long...)

See the example below:

#ifdef FLAG1
    struct str{
        int i1;
        long l1;
        doulbe d1;
    };
#elsif defined (OPTION2)
    struct str{
        double d1
        long l1;
    };
#else
    struct str{
        int i1;
    };
#endif

I guess a good pseudo-code for what I want to do is:

void f (str * toZero)
{
    foreach member m in toZero
        m=0
}

Is there a way to easily do that in c++?

To initialise any PODO's data to zero in C++ use = { 0 } . You don't need to iterate over every member.

StructFoo* instance = ...
*instance = { 0 };

For simplicity, You may want to consider using a single macro in the following way:

#define NUMBER_OF_MEMBERS 3

struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1;
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1;
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1;
#endif
};

void f (Str & str){

    #if NUMBER_OF_MEMBERS > 0
        str.i1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 1
        str.d1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 2
        str.l1 = 0;
    #endif

    return;
}

int main() {
    Str str;
    f(str);
}

Secondly, are you only calling the f function after you create the class to start the values at zero? If so, this is better suited for the struct's constructor method. In C++11, it could be written as cleanly as this:

#define NUMBER_OF_MEMBERS 3

struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1 = {0};
#endif
};

int main() {
    Str str;
    //no need to call function after construction
}

If the struct members are enabled and disabled by defines, then there is no other possiblity than to use the same defines for access to values of the struct . However, a struct might not be the best choice if flexibility is needed.

您可以使用C-way,因为它是一个pod:

memset(&str_instance, '\0', sizeof(str));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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