I have a for loop that I want to use multiple times without copy and pasting the code so I'm using a template. Answer I used for the template. The template and loop itself work as intended, but changing a variable from the list inside the function called inside the for loop doesn't work. If I change s.Color inside the 'Test' function, it has not changed outside of that function or the example loop.
So why it is not changed outside of the loop? And how can I make sure it changes 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);
}
}
Calling the template:
do_something_loop(Test);
The 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;
};
I suppose:
void Test(TrafficLight s) { ... }
should be:
void Test(TrafficLight& s) { ... }
because now you edit a copy.
So need to pass by reference instead.
Change this:
void Test(TrafficLight s)
to this:
void Test(TrafficLight& s)
since you need to pass by reference in order for the changes to persist after the function is terminated.
Your code passes the argument by value (it creates a copy of s
inside th body of Test()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With