[vtk-developers] Members of smartpointers as observers

David Gobbi david.gobbi at gmail.com
Sat Oct 9 16:50:32 EDT 2010


On Sat, Oct 9, 2010 at 8:46 AM, David Doria <daviddoria at gmail.com> wrote:
> On Sat, Oct 9, 2010 at 10:36 AM, Utkarsh Ayachit
> <utkarsh.ayachit at kitware.com> wrote:
>> How about
>>
>>  renderWindowInteractor->AddObserver(vtkCommand::KeyPressEvent,
>>  style2.GetPointer(), &MyInteractorStyle::KeypressCallbackFunction)
>>
>> Utkarsh
>
> That works. Should we make an overload in vtkObject?
>
> Something like:
>
> unsigned long AddObserver(unsigned long event,
>    vtkSmartPointer<T> observer, void (T::*callback)(), float priority=0.0f)
> {
>  AddObserver(event, observer.GetPointer(), callback, priority);
> }

The conversion from SmartPointer to regular pointer can be handled
automatically by the templates:

  template <class U, class T>
  unsigned long AddObserver(unsigned long event,
    U observer, void (T::*callback)(), float priority=0.0f)
    {
    vtkClassMemberCallback<T> *callable =
      new vtkClassMemberCallback<T>(observer, callback);
    // callable is deleted when the observer is cleaned up (look at
    // vtkObjectCommandInternal)
    return this->AddTemplatedObserver(event, callable, priority);
    }

This will compile as long as vtkClassMemberCallback<T> can be
constructed with a "U" in place of a "T *". It takes advantage of the
smart pointer's "operator T* ()" and it will also work with weak
pointers or any other kind of special "pointers".  It is safe, because
it will fail to compile if "U" cannot be made into a "T *".

I'll commit once I've added this to the test.

  David



More information about the vtk-developers mailing list