0
// Library code
struct Entity;
struct Attachment { 
    Entity& entity;
    Attachment(Entity& mEntity) : entity(mEntity) { }
};

// ---
// User code
struct MyAttachment1 : Attachment { 
    // This is annoying to write for every attachment type
    // Especially when there are other constructor arguments
    // And if there are a lot of attachment types
    MyAttachment1(Entity& mEntity) : Attachment{mEntity} { }
};
struct MyAttachment2 : Attachment { 
    MyAttachment2(Entity& mEntity) : Attachment{mEntity} { }
};
// ...

コード例からわかるように、から派生するすべての型は、基本クラスのコンストラクターに渡される繰り返しコンストラクターAttachmentを定義する必要があります。Entity&

これは問題にはなりませんが、私のプロジェクトでは 40 ~ 50 以上のアタッチメントを扱っており、コンストラクターには独自のパラメーターもあります。

Entity&最初のパラメーターとして明示的に渡す必要はないようです。

私が見つけた 1 つの回避策はvirtual void Attachment::init()、ユーザーがオーバーライドし、が追加されたEntity後にによって呼び出されるメソッドを使用することです。Attachmentただし、これは不必要なvirtual呼び出しを使用し、ユーザーがボイラープレート コードを処理する必要があります。

この問題に対処するためのよりエレガントな方法はありますか?

4

2 に答える 2

0

いいえ、これ以上エレガントな書き方はありません。クラスコンストラクターを書いているときのタイピングがどれほどAttachment{mEntity}雑用と見なされるのか、私には理解できません。とにかく、あなたはクラス全体を書いています。面倒な場合は、テキスト エディタでマクロを作成してください。

于 2013-10-23T14:57:19.670 に答える
0

それが役立つかどうかはわかりませんが、C++ 11では次のこともできます

struct MyAttachment1 : Attachment { 
    // Note, this imports ALL of the base constructors, you can't 
    // pick and choose
    using Attachment::Attachment;

};

https://ideone.com/fceV4kを参照

于 2013-10-23T15:00:19.570 に答える