我想编写一个包装类,所有运算符都被重载,以便我可以检测何时写入/读取或修改其内容。例如:

probe<int> x;
x = 5;     // write
if(x) {    // read
   x += 7; // modify
}

有人已经这样做了吗?如果不是我必须超载哪些操作员以确保我不会错过任何东西?

有帮助吗?

解决方案

我想,你不能。操作员?:不可超载。此外,如果T::T(int)已定义,则T foo = 4是合法的,但T foo = probe<int>(4)则不合法。最多只有一个用户定义的转换。

此外,由于探针不是POD,程序的行为可能会发生变化。

其他提示

将此作为一个常见的想法。 像<!> amp; = | = []这样的运算符很多,在你的情况下可能不是主体。

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;
    }
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top