fa.'s answer 좋은 시작이다 : 그럼 당신은 신고자 내부 사용할 수있는 소유의 방법이있을 수 있습니다. 그러나 동일한 유형의 소유자가 여러 명있는 문제는 해결되지 않습니다. 한 가지 해결책은 통보자가 단일 목록 대신 소유자 목록을 저장하도록하는 것입니다.
template <typename Owner, typename Owned>
class Notifier
{
protected:
Notifier()
{}
// Constructor taking a single owner
Notifier(Owner & o)
{
owners.push_back(&o);
}
// Constructor taking a range of owners
template <typename InputIterator>
Notifier(InputIterator firstOwner, InputIterator lastOwner)
: owners(firstOwner, lastOwner) {}
~Notifier()
{
OwnerList::const_iterator it = owners.begin();
OwnerList::const_iterator end = owners.end();
for (; it != end ; ++it)
{
(*it)->notify(static_cast<Owned*>(this));
}
}
// Method for adding a new owner
void addOwner(Owner & o)
{
owners.push_back(&o);
}
private:
typedef std::vector<Owner *> OwnerList;
OwnerList owners;
};
당신이 이런 식으로 사용할 수 있습니다 : 여기에 빠른 구현이 아이디어를 보여주고, 당신이 소유자의 많은 다른 유형이있는 경우
class Owner;
class Owned : public Notifier<Owner, Owned>
{
typedef Notifier<Owner, Owned> base;
//Some possible constructors:
Owned(Owner & o) : base(o) { }
Owned(Owner & o1, Owner & o2)
{
base::addOwner(o1); //qualified call of base::addOwner
base::addOwner(o2); //in case there are other bases
}
Owned(std::list<Owner*> lo) : base(lo.begin(), lo.end()) { }
};
을,이 솔루션은 오히려 어려워 질 수 있습니다 사용. 것이 솔루션을 구현, 그러나
class Owned : public Notifier<Owned, OwnerType1, OwnerType1, OwnerType2>
{
Owned(OwnerType1 & o1, OwnerType1 & o2, OwnerType2 & o3)
: base(o1,o2,o3)
};
:이 경우, 당신은 당신이 그런 식으로 물건을 할 수 있도록 코드로 끝낼 수있는 부스트 메타 프로그래밍 라이브러리 (MPL, Fusion),보고 할 수 있습니다 이전보다 조금 길어.
정적 다형성이 필요합니까 아니면 예를 들어 기본 기본 클래스 IOwner를 만들 수 있습니까? 순수한 가상 메소드가 '통지'됩니까? –
아니요, 순수한 가상 '알림'을 가질 수 없습니다. –