我想编写一个所有运算符都重载的包装类,这样我就可以检测到我们何时写入/读取或修改其内容。例如:
probe<int> x;
x = 5; // write
if(x) { // read
x += 7; // modify
}
有人做过吗?如果不是,我必须重载哪些运算符以确保我不会错过任何东西?
最佳答案
将此作为一个共同的想法。 有很多像 and= |= [] 这样的运算符在你的情况下可能不是主要的。
template < typename T >
struct monitor
{
monitor( const T& data ):
data_( data )
{
id_ = get_next_monitor_id();
}
monitor( const monitor& m )
{
id_ = get_next_monitor_id();
m.notify_read();
notify_write();
data_ = m.data_;
}
operator T()
{
notify_read();
return data_;
}
monitor& operator = ( const monitor& m )
{
m.notify_read();
notify_write();
data_ = m.data_;
return *this;
}
monitor& operator += ( const monitor& m )
{
m.notify_read();
notify_write();
data_ += m.data_;
return *this;
}
/*
operator *=
operator /=
operator ++ ();
operator ++ (int);
operator -- ();
operator -- (int);
*/
private:
int id_;
T data_;
void notify_read()
{
std::cout << "object " << id_ << " was read" << std::endl;
}
void notify_write()
{
std::cout << "object " << id_ << " was written" << std::endl;
}
};
关于c++ - 使用运算符重载 c++ 进行监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/606135/