I recently stumbled up this proxy class for making c++ primitive members "read only" (publicly act as const references, but privately non const). This potentially eliminates the need for boilerplate "getters". The proxy class looks like:
template <Container,Primitive>
class RO
{
friend Container;
public:
inline operator Primitive() const { return x; }
template<typename Other> inline bool operator==(const Other& y) const { return x == y; }
template<typename Other> inline bool operator!=(const Other& y) const { return x != y; }
template<typename Other> inline bool operator< (const Other& y) const { return x < y; }
template<typename Other> inline bool operator> (const Other& y) const { return x > y; }
template<typename Other> inline bool operator<=(const Other& y) const { return x <= y; }
template<typename Other> inline bool operator>=(const Other& y) const { return x >= y; }
template<typename Other> inline Other operator+ (const Other& y) const { return x + y; }
template<typename Other> inline Other operator- (const Other& y) const { return x - y; }
... // all other const operator overloads
protected:
inline RO() :x(){ }
template<typename Other> inline RO(const Other& y) :x(y) { }
template<typename Other> inline Primitive& operator= (const Other& y) { return x = y; }
template<typename Other> inline Primitive& operator+=(const Other& y) { return x += y; }
template<typename Other> inline Primitive& operator-=(const Other& y) { return x -= y; }
template<typename Other> inline Primitive& operator*=(const Other& y) { return x *= y; }
template<typename Other> inline Primitive& operator/=(const Other& y) { return x /= y; }
... // all other non-const operator overloads
inline Primitive* ptr() { return &x; }
inline Primitive& ref() { return x; }
inline const Primitive* const_ptr() const { return &x; }
inline const Primitive& const_ref() const { return x; }
Primitive x;
};
This seems to work as desired if I have a flat class structure: just some class A
which has RO
proxy's for its read-only members. But as soon as I have some derived class B : public A
, then I get into trouble. I'd like to have B
read and write to the read-only RO
members of defined in the inherited class A
. But seeing as friendship is non-inherited. I'm not sure how to go about this. Same applies to direct friends of A
: friendship is non-transitive.
Is there a construction of "read-only" proxies which are writable to friends and derived classes?