Suppose we have an object Foothat allows you to:
cout << myFoo[3];
myFoo[5] = "bar";
This requires a proxy design template ( see Scott Meyers for details )
But now let's assume that each is myFoo[i]also an instance Foo.
myFoo[7] = Foo{...};
myFoo[5] = "bar"; // Foo has a Foo(std::string) non-explicit constructor
I am close to implementation, but I can’t get rid of one last annoying error "preliminary declaration / incomplete type".
First, let's clean the easy way:
const Object operator[] (const Object& key) const {
return Object{ PyObject_GetItem(p, key.p) };
}
Here is the basic non-recursive proxy pattern:
Proxy operator [] ( const Object& key ) { return Proxy{ *this, key }; }
class Proxy {
private:
const Object& container;
const Object& key;
public:
Proxy( const Object& c, const Object& k ) : container{c}, key{k}
{ }
operator Object() const {
return container[key];
}
const Object& operator= (const Object& rhs_ob) {
PyObject_SetItem( container.p, key.p, rhs_ob.p );
return rhs_ob;
}
#if 0
const Proxy& operator= (const Proxy& rhs) {
PyObject_SetItem( pContainerObj->p, pKeyObject->p, static_cast<Object>(rhs).p );
return rhs;
}
#endif
};
Not sure if I need the last handler.
In any case, to make it recursive, we need:
class Proxy : Object {
:
, Proxy Object, " ".
, . , , :
class Object::Proxy : public Object {
private:
const Object& container;
const Object& key;
public:
Proxy( const Object& c, const Object& k )
: container{c}, key{k}, Object{c[k]}
{ }
, Object, --:
#if 0
operator Object() const {
return container[key];
}
#endif
, .
Object::Proxy (, ) Object,
Proxy operator [] ( const Object& key ) { return Proxy{ *this, key }; }
... , (Proxy). , , - Proxy. Proxy* . Proxy .
, Catch-22, .
?
: , , , , Object . PyObject* PyObject*.
: , ,