Den*_*sof 2 c++ c++11 c++14 c++17
我有一个带有两个重载括号运算符的自定义类-setter和getter。如您所知,它们看起来像这样
class IntContainer {
public:
int const & operator[] (size_t i) const;
int & operator[] (size_t i);
}
Run Code Online (Sandbox Code Playgroud)
我现在面临的问题是,我必须检查何时设置了值或何时刚刚访问了值,也就是说,我需要跟踪容器中的所有更改。很难,因为总是只const调用非运算符
container[i] = 3; // Non const operator[] called
x = container[i]; // Again, non const operator[] called
Run Code Online (Sandbox Code Playgroud)
在上述两种情况下,我需要改变容器的内部行为。在上述情况下,有没有办法显式调用不同的运算符。我不想使用const容器的实例并定义另一个函数,例如set和get,尽管我正在寻找合适的设计模式。
谢谢!
One trick is to create a proxy 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; }
};
Run Code Online (Sandbox Code Playgroud)
then you can adjust IntContainer to
class IntContainer {
public:
int operator[] (size_t i) const;
Proxy operator[] (size_t i);
};
Run Code Online (Sandbox Code Playgroud)
and now you'll call the tracking code when the user actually tries to assign into the reference.
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |