我想编写一个所有运算符重载的包装类,以便我可以检测我们何时写入/读取或修改其内容。例如:
probe<int> x;
x = 5; // write
if(x) { // read
x += 7; // modify
}
有人已经这样做了吗?如果不是,我必须重载哪些运算符以确保我不会错过任何内容?
我想编写一个所有运算符重载的包装类,以便我可以检测我们何时写入/读取或修改其内容。例如:
probe<int> x;
x = 5; // write
if(x) { // read
x += 7; // modify
}
有人已经这样做了吗?如果不是,我必须重载哪些运算符以确保我不会错过任何内容?
将此作为一个常见的想法。有很多像 &= |= [] 这样的运算符在您的情况下可能不是主要的。
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;
}
};
你不能,我想。operator?: 不可重载。此外,如果T::T(int)
已定义,T foo = 4
则合法但T foo = probe<int>(4)
不合法。最多有一个用户定义的转换。
此外,由于探针不是 POD,因此程序的行为可能会发生变化。