mardi 8 janvier 2019

print all nested member variables of a struct with a generic function call

Let's say, I have the following nested struct definition,

struct C {
    int r;
    char s;
};
struct B {
    int p;
    char q;
    C c;
};
struct A {
    int x;
    int y;
    B b;
    char z;
};

I need a pretty_print(A &a) function which prints all the member variables with proper indentation. I could do it in the following way:

#include <iostream>
struct C {
    int r;
    char s;
};
struct B {
    int p;
    char q;
    C c;
};
struct A {
    int x;
    int y;
    B b;
    char z;
};

void pretty_print(A &a) {
    std::cout << a.x << std::endl;
    std::cout << a.y << std::endl;
    std::cout <<"\t"<< a.b.p << std::endl;
    std::cout <<"\t"<< a.b.q << std::endl;
    std::cout <<"\t\t"<< a.b.c.r << std::endl;
    std::cout <<"\t\t"<< a.b.c.s << std::endl;
    std::cout << a.z << std::endl;

}
int main() {
    A a{1, 2, {3, 'p', {4, 'k'}}, 'w'};
    pretty_print(a);
}

Is there a way to have a member (or non-member) function (generic function, written only once) that takes struct A and automatically figures out its member variables and prints them with proper indentation? (basically, the required function definition should not change if we change the type of member variable or add or remove member variables)

Thanks!

Aucun commentaire:

Enregistrer un commentaire