This question has already been answered:

I want to create a function that will run over all the fields of the class and set them to values, either 0 if the field is numeric, or an empty string, if the field is string.

Something like that func<Class>(obj);

Since all the classes are different and their fields are different, and in C ++ there is almost no runtime, then apparently this should be done at the compilation stage, apparently through templates.

Is it possible, or is the C ++ template engine not developed enough to do such things?

Maybe there is some kind of trick with macros?

Reported as a duplicate by the participants αλεχολυτ , user194374, Harry c ++ 10 Feb '17 at 13:36 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 3
    There is no meta information about classes in C ++. - Chorkov
  • Recently discussed like. In general, you just need to set the default constructor. - αλεχολυτ
  • @alexolut, what is the default constructor, if I want to make a bridge from the C ++ world to the javascript world in the Cheerp translator so that the script creates a wrapper object that sends C ++ signals to the object. For this, I need to know clearly each field of the C ++ class. In order not to write with hands JS vrapper for every C ++ class - Maxmaxmaximus
  • What does any bridge have to do with JS, if you haven’t written anything about this? Initialization tasks are decided in the constructor . - αλεχολυτ
  • four
    In the question, the task should be described so that it is clear what the author wants. - αλεχολυτ

1 answer 1

The option to clean the structure based on the answer previously mentioned in the comments:

 #include <iostream> #include <string> #define STRUCT_FIELDS \ X(int, i) \ X(double, d) \ X(std::string, c) struct S { #define X(type, name) type name; STRUCT_FIELDS #undef X }; template<typename T> void f(T& t) { t = T(); } void clear(S& s) { #define X(type, name) f(s.name); STRUCT_FIELDS #undef X } int main() { S s { 1, 42.1, "c" }; std::cout << si << "[" << sc << "]" << sd << "\n"; clear(s); std::cout << si << "[" << sc << "]" << sd << "\n";; } 

Result of performance:

 1[c]42.1 0[]0