Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing list inside template not saving

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;
};
like image 973
Stefan Teunissen Avatar asked Nov 23 '17 09:11

Stefan Teunissen


2 Answers

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.

like image 71
Edgar Rokjān Avatar answered Oct 20 '22 09:10

Edgar Rokjān


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()).

like image 25
gsamaras Avatar answered Oct 20 '22 10:10

gsamaras