monitor with operator overloading c++
-
03-07-2019 - |
Question
I would like to write a wrapper class with all operators overloaded such that I can detect when we write/read or modify its contents. For instance:
probe<int> x;
x = 5; // write
if(x) { // read
x += 7; // modify
}
Anyone already did that? If not which operators must I overload to be sure I dont miss anything?
Solution
You can't, I think. operator?: isn't overloadable. Also, if T::T(int)
is defined, T foo = 4
is legal but T foo = probe<int>(4)
isn't. There's at most one user-defined conversion.
Furthermore, because probe is not a POD, the behavior of your program can change.
OTHER TIPS
Use this as a common idea. There are plenty of operators like &= |= [] which maybe are not principal in your case.
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;
}
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow