2

以下を可能にするFooオブジェクトがあるとします。

cout << myFoo[3];
myFoo[5] = "bar";

これには、プロキシの設計パターンが必要です ( Scott Meyers による詳細はこちら) 。

しかしここで、everymyFoo[i]Fooインスタンスであるとしましょう。

myFoo[7] = Foo{...};
myFoo[5] = "bar"; // Foo has a Foo(std::string) non-explicit constructor

私は実装に近づいていますが、最後の厄介な「前方宣言/不完全型」エラーを取り除くことはできません。

まず、簡単なものから始めましょう。

// x = someConstObject[4], so this must be Rvalue access
//  i.e. someConstObject[4] = ... would be a contradiction / const violation
const Object  operator[] (const Object& key)  const { 
    return Object{ PyObject_GetItem(p, key.p) };
}

基本的な非再帰プロキシ パターンは次のとおりです。

Proxy operator [] ( const Object& key ) { return Proxy{ *this, key }; }

class Proxy {
private:
    const Object& container;
    const Object& key;

public:
    // at this moment we don't know whether it is 'container[key] = x' or 'x = container[key]'
    Proxy( const Object& c, const Object& k ) : container{c}, key{k}
    { }

    // Rvalue
    // e.g. cout << myList[5] 
    operator Object() const {
        return container[key]; // <-- invokes the original const [] overload
    }

    // Lvalue
    // e.g. myList[5] = foo
    const Object&  operator= (const Object& rhs_ob) {
        PyObject_SetItem( container.p, key.p, rhs_ob.p );
        return rhs_ob; // allow daisy-chaining a = b = c etc.
    }

    #if 0 
    // I think this should come for free, as the above Rvalue handler 
    //     ... collapses a Proxy into an Object

    // e.g. myList[5] = someOtherList[7]
    const Proxy&  operator= (const Proxy& rhs) {
        // Force resolution of rhs into Object
        PyObject_SetItem( pContainerObj->p, pKeyObject->p, static_cast<Object>(rhs).p /* rhs.value->p*/ );
        return rhs;
    }
    #endif
    // ^ Note: allows:
    // e.g. x = y[1] = z[2];  // <-- y[1] must return an Object
    // e.g. if( y[1] = z[2] ) // <-- assigns and then checks that y[1] evaluates to true
};

その最後のハンドラーが必要かどうかわかりません。

とにかく、再帰的にするには、次のものが必要です。

    class Proxy : Object {
        :

Proxyこれは、内で定義できなくなったことを意味しますObject。そうしないと、「不完全な型をベースにしようとしています」というコンパイラ エラーが発生します。

では、そうしましょう。また、可能な場合はコンストラクターを変更して基本クラスを埋める必要があります。

class Object::Proxy : public Object {
private:
    const Object& container;
    const Object& key;

public:
    // at this moment we don't know whether it is 'c[k] = x' or 'x = c[k]'
    // If it's 'c[k] = x', setting the base class to c[k] is going to 
    //     either set it to the old value of c[k]
    //     or a None object (if it didn't have any value previously)
    // we had better be certain to make sure the original c[k] overload 
    //     returns None if unsuccessful
    Proxy( const Object& c, const Object& k ) 
        : container{c}, key{k}, Object{c[k]} // <-- might fail!
    { }

そして、Object基本クラスにより、typecast-to-object を手動で処理する必要がなくなります。

    // Rvalue
    // e.g. cout << myList[5] hits 'const Object operator[]'
    #if 0
    // it looks as though we don't need to do this given that 
    //    we now have Object as base class
    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*データ メンバーは 1 つだけです。

編集:私が取り組んでいる元のコードはここにあります

4

2 に答える 2

2

あなたの前提には欠陥があるようです。定義上、AはProxy ではありません。Objectもしそうなら、そもそもそれを a とは呼ばないでしょうProxy。そして、必要に応じて新しく作成されたへの参照を返すstd::mapだけで、標準のデータ型が問題を解決するのと同じ方法で、プロキシなしで問題を解決できます。operator[]Object

std::vector<bool>のプロキシ パターンのようなものを探しています: をoperator[]返し、Proxyoperator=プロキシへの暗黙的な変換を返しますObject(実際に値を代入するのではなく、値を使用したい場合)。

class Object {
    struct Proxy {
        PyObject *container;
        PyObject *key;
        Proxy(PyObject *c, PyObject *k): container(c), key(k) {}
        Proxy& operator= (const Object& value) { 
            PyObject_SetItem(container, key, value.p); 
            return *this; 
        }
        operator Object() const {
            PyObject *p = PyObject_GetItem(container, key);
            if (p == nullptr) throw "proxy was not backed by a real object";
            return p;
        }
    };

    PyObject *p;
    Object(PyObject* p): p(p) {}

public:
    Object operator[] (const Object& key) const { 
        return PyObject_GetItem(p, key.p); 
    }
    Proxy operator[] (const Object& key) { return {p, key.p}; }
};
于 2014-12-28T23:16:41.527 に答える
1

私は最終的にこれを解決しました。

秘訣は、クラスを独自のプロキシとして単純に使用することです。

そのため、もともと Proxy オブジェクトは左辺値アクセスと右辺値アクセスを区別するための変換を提供していましたが、これらの変換を元のオブジェクト クラスに戻すだけです。

    mutable bool m_resolve_me{false};
    PyObject* m_container{nullptr};
    PyObject* m_key{nullptr};

public:
    // Rvalue (e.g. x = ob[42];)
    const Object operator[] (const Object& key)  const { 
        return Object{ PyObject_GetItem( p, key.p ) }; 
    } 

    // Don't know yet
    Object operator[] (const Object& key) { 
        return Object{ *this, key }; 
    }

    // notice we set the m_resolve_me flag
    // as we don't yet know L/Rvalue-ness
    Object( const Object& c, const Object& k )
        : m_container{c.p}, m_key{k.p}, m_resolve_me{true}
    {
        // for all but lvalue access (ob[idx]=...), ob[idx] will be valid
        p = PyObject_GetItem( m_container, m_key ); 

        if( p == nullptr ) {
            // ... However in the case of lvalue access, 
            // PyObject_GetItem will set Python's error indicator
            // so we must flush that error, as it was expected!
            PyErr_Clear();
            p = charge(Py_None);
        }
        // ^ either way, p ends up charged
    }

public:
    // this will attempt to convert ANY rhs to Object, which takes advantage of ALL the above constructor overrides
    Object& operator=( const Object& rhs )
    {
        /*
            1) normal situation
            2) this object is m_resolve_me, and we are assigning 
                 a normal object to it
            3) this object is m_resolve_me, and we are assigning 
                 a m_resolve_me object to it
            4) this object is normal, and we are assigning a m_resolve_me object to it

            1) we need to charge p
            2) same
            3) same
            4) same

            The only important thing is: we have to be neutral to rhs.p
            That means we have to charge it, as we will be 
               subsequently neutralising it in the destructor
         */
        if( &rhs != this )
            *this = charge(rhs.p);

        return *this;
    }

    // (Always) assume charged pointer
    Object& operator=( PyObject* pyob )
    {
        if( m_resolve_me ) {
            PyObject_SetItem( m_container, m_key, pyob );
            m_resolve_me = false;
        }

        set_ptr( pyob );

        return *this;
    }
于 2015-01-18T14:37:52.860 に答える