// 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
呼び出しを使用し、ユーザーがボイラープレート コードを処理する必要があります。
この問題に対処するためのよりエレガントな方法はありますか?