문제

내용을 쓰거나 읽거나 수정할 때 감지 할 수 있도록 모든 연산자가 과부하가 걸린 래퍼 클래스를 쓰고 싶습니다. 예를 들어:

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

이미 그랬어? 어떤 연산자가 내가 아무것도 놓치지 않는지 확인하기 위해 어떤 연산자가 과부하되어야합니까?

도움이 되었습니까?

해결책

당신은 할 수 없습니다. 연산자? : 과부하 할 수 없습니다. 또한 IF T::T(int) 정의됩니다. T foo = 4 합법적이지만 T foo = probe<int>(4) 그렇지 않습니다. 최대 하나의 사용자 정의 변환이 있습니다.

또한 프로브는 포드가 아니기 때문에 프로그램의 동작이 변경 될 수 있습니다.

다른 팁

이것을 일반적인 아이디어로 사용하십시오. & = | = []와 같은 많은 운영자가 있습니다.이 경우에는 원금이 아닙니다.

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