c++proxy-pattern

proxy class in rvalue - how to implement assignment operator?


Suppose I have a simple vector class where elements are accessed through a proxy class.

Vector class:

class vec {
public:
    vec(int len) {
        length = len;
        data = new double [len];
    }

    proxy operator[](int i) {
        if (i >= 0 && i < length) {
            return proxy(i, data);
        }
        else {
            std::cerr << "AHHHH!\n";
            exit(1);
        }
    }
private:
    int length;
    double * data;
};

Proxy class:

class proxy {
public:
    proxy(int i, double * d) {
        index = i;
        data  = d;
    }

    void operator=(double rhs) {
        data[index] = rhs;
    }

private:
    int index;
    double * data;
};

How can I assign elements from the vector (or rather, from the proxy) to a variable of type double? In other words, how do I accomplish the following:

int main() {
    vec a(2);
    double x = 3.14;
    a[0] = x; // Works!
    x = a[0]; // How to make work?

    return 0;
}

Unfortunately, I can't write something like:

friend double operator=(double & lhs, const proxy & p) { ... }

since operator= must be a member.


Solution

  • Add a conversion function to your proxy class:

    class proxy
    {
    public:
        operator double() const { return data[index]; }
    
        // ...
    };