简体   繁体   中英

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;
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM