简体   繁体   English

自定义容器中括号运算符中的常量

[英]Constness in brackets operator in custom container

I have a custom class with two overloaded brackets operators -- setter and getter.我有一个自定义的 class 带有两个重载的括号运算符——setter 和 getter。 As you know they look somewhat like this如你所知,它们看起来有点像这样

class IntContainer {
public:
    int const & operator[] (size_t i) const;
    int & operator[] (size_t i);
}

The problem I'm facing now, is that I have to check when the value was set or when it was just accessed, that is I need to track all the changes in my container.我现在面临的问题是,我必须检查值的设置时间或刚刚访问的时间,即我需要跟踪容器中的所有更改。 It's hard since always only non const operator is called, for example这很难,因为总是只调用非常const运算符,例如

container[i] = 3;  // Non const operator[] called
x = container[i];  // Again, non const operator[] called

In two cases above I need to differ inner behavior in container.在上述两种情况下,我需要区分容器中的内部行为。 So is there any way to explicitly call different operators in cases like above.那么在上述情况下,有什么方法可以显式调用不同的运算符。 I don't want to use const instance of container and to define another functions like set and get , though I'm looking for smoe right design pattern.我不想使用容器的const实例并定义其他函数,例如setget ,尽管我正在寻找正确的设计模式。

Thanks!谢谢!

One trick is to create a proxy object.一个技巧是创建一个代理 object。 This lets you overload the assignment operator and put your tracking logic into there and then you can guarantee that any writes are captured.这使您可以重载赋值运算符并将跟踪逻辑放入其中,然后您可以保证捕获任何写入。 If you have如果你有

class Proxy
{
    int& val;
    Proxy(int& val) : val(val) {}
    Proxy& operator=(int new_val)
    {
        // do tracking stuff
        val = new_val;
    }
    operator int() { return val; }
};

then you can adjust IntContainer to那么您可以将IntContainer调整为

class IntContainer {
public:
    int operator[] (size_t i) const;
    Proxy operator[] (size_t i);
};

and now you'll call the tracking code when the user actually tries to assign into the reference.现在您将在用户实际尝试分配给参考时调用跟踪代码。

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

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