Editing a list inside a template is not saved

I have a for loop that I want to use several times without copying and pasting the code, so I use a template. The answer I used for the template. The template itself and the loop work as intended, but changing a variable from a list inside a function called inside a for loop does not work. If I changed s.Color inside the "Test" function, it has not changed outside of this function or example loop.

So why doesn't it change outside of the loop? And how can I make sure it has changed outside of the loop?

Template:

void Test(TrafficLight s) { switch (s.Type) { case hfdWeg: s.Color = queueCurrent.HoofdwegColor; break; case zWeg: s.Color = queueCurrent.ZijwegColor; break; case vtPad: s.Color = queueCurrent.VoetpadColor; break; default: std::cout << "\nError"; break; } } template<typename Func> inline void do_something_loop(Func f) { for (std::list<TrafficLight>::iterator i = Lichten.begin(); i != Lichten.end(); ++i) { TrafficLight & s(*i); f(s); } } 

Template call:

 do_something_loop(Test); 

List:

 std::list<TrafficLight> Lichten; 

TrafficLight Class:

 class TrafficLight { private: public: TrafficLight(TrafficLightType type, TrafficLightColor color = R) { Color = color; Type = type; } TrafficLightColor Color; TrafficLightType Type; }; 
+5
source share
2 answers

I suppose:

 void Test(TrafficLight s) { ... } 

it should be:

 void Test(TrafficLight& s) { ... } 

because now you are editing a copy.

So you need to pass by reference.

+5
source

Change this:

 void Test(TrafficLight s) 

:

 void Test(TrafficLight& s) 

since you need to follow the link so that the changes are saved after the function is completed.

Your code passes the argument by value (it creates a copy of s inside the body of Test() ).

+2
source

Source: https://habr.com/ru/post/1273607/


All Articles