c++ - Call function with all instances of a struct -
i want call function struct objects.
i need function can loop through struct-objects a_1, a_2 calling struct struct_a. empty function 'reset_all_structs( ??? )' @ bottom of code.
sample code:
#include <iostream> struct struct_a { unsigned char number = 0; bool bool_1 = 0; bool bool_2 = 0; } a_1, a_2; // objects: maybe later a_3, ... , a_x void print_to_terminal(struct_a &struct_name); void set_bool_1(struct_a &struct_name); void set_bool_2(struct_a &struct_name); void reset_one_struct(struct_a &struct_name); void reset_all_structs(); int main() { set_bool_1(a_1); a_1.number = 111; set_bool_2(a_2); a_2.number = 222; std::cout << "a_1:\n"; print_to_terminal(a_1); std::cout << "\n"; std::cout << "a_2:\n"; print_to_terminal(a_2); std::cout << "\n"; reset_one_struct(a_1); // <-- reset 1 struct works, question ist how reset structs type struct_a? std::cout << "a_1:\n"; print_to_terminal(a_1); std::cout << "\n"; set_bool_2(a_1); a_1.number = 234; std::cout << "a_1:\n"; print_to_terminal(a_1); std::cout << "\n"; // here question. ??? // reset_all_structs( struct_a ); // want reset both a_1 , a_2 calling function reset_all_structs object of struct "struct_a" , loop through these. possible // don't want call function reset_all_struct(a_1, a_2) because later add more objects of struct struct_a. std::cout << "reset a_1 , a_2\n"; std::cout << "a_1:\n"; print_to_terminal(a_1); std::cout << "\n"; std::cout << "a_2:\n"; print_to_terminal(a_2); std::cout << "\n"; return 0; } void print_to_terminal(struct_a &struct_name){ std::cout << "number: " << (int)struct_name.number << "\n"; std::cout << "bool_1: " << (int)struct_name.bool_1 << "\n"; std::cout << "bool_2: " << (int)struct_name.bool_2 << "\n"; return; }; void set_bool_1(struct_a &struct_name){ struct_name.bool_1 = 1; struct_name.bool_2 = 0; return; }; void set_bool_2(struct_a &struct_name){ struct_name.bool_1 = 0; struct_name.bool_2 = 1; return; }; void reset_one_struct(struct_a &struct_name){ struct_name.number = 0; struct_name.bool_1 = 0; struct_name.bool_2 = 0; return; }; void reset_all_structs( ??? ){ // loop through structs return; };
the language doesn't have possibility iterate through same variables of same types.
you can make sort of registry of structs , iterate through registry. like:
struct struct_a; std::vector<struct_a*> struct_a_registry; struct struct_a { ... // constructor struct_a() { struct_a_registry.push_back(this); } // destructor ~struct_a() { (std::vector<struct_a*>::iterator = struct_a_registry.begin(); != struct_a_registry.end(); ++it) if (*it == this) { struct_a_registry.erase(this); break; } } };
then reset_all_structs just
void reset_all_structs() { (std::vector<struct_a*>::iterator = struct_a_registry.begin(); != struct_a_registry.end(); ++it) reset_one_struct(**it); }
or, if declaring struct_a variables @ same line of program, can organize them array, simpler.
Comments
Post a Comment