简体   繁体   English

编辑模板内的列表不保存

[英]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. 我有一个for循环,我想多次使用没有复制和粘贴代码所以我使用模板。 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. 模板和循环本身按预期工作,但是从for循环中调用的函数内的列表中更改变量不起作用。 If I change s.Color inside the 'Test' function, it has not changed outside of that function or the example loop. 如果我在'Test'函数中更改s.Color,它在该函数或示例循环之外没有更改。

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: TrafficLight类:

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() ). 你的代码按值传递参数(它在Test()体内创建一个s副本 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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