Xav*_*det 7 c++ notifications templates one-to-many
我想在C++中创建一个Notifier类,我将在其他对象中使用它来在对象被销毁时通知各个持有者.
template <class Owner>
class Notifier<Owner> {
public:
Notifier(Owner* owner);
~Notifier(); // Notifies the owner that an object is destroyed
};
class Owner;
class Owned {
public:
Owned(Owner* owner);
private:
Notifier<Owner> _notifier;
};
Run Code Online (Sandbox Code Playgroud)
我的观点是,由于我有一个密集而复杂的对象图,我想避免将所拥有对象的地址存储在通知程序中.有没有办法更改我的通知程序类,以便它可以从自己的地址推导出拥有对象的地址,以及在编译时计算的偏移量?
另请注意,任何对象可能必须通知几个"所有者",可能来自同一个类.
谢谢.
或者像这样的东西:
从通知程序继承并添加 Owned 作为模板参数。然后你可以在通知程序中使用一个拥有的方法:
template < class Owner , class Owned >
class Notifier
{
public:
Notifier(Owner* owner)
{}
Owned * owned()
{ return static_cast< Owned * >( this ); }
~Notifier()
{
// notify owner with owned()
}
};
class Owner
{};
class Owned : public Notifier< Owner , Owned >
{
public:
Owned( Owner * owner ) : Notifier< Owner , Owned >( owner )
{}
};
Run Code Online (Sandbox Code Playgroud)