Command/Observer which accepts a lambda

Hello,

I am wondering if anyone has already created a itk::Command class which accepts a C++ lambda function?

Otherwise, I am wondering if a new itk::Object::AddObserver method should be overloaded to accept std::function<void()> so that a lambda can be directly added instead of constructing a command class.

What do you think?

3 Likes

Sounds like a great idea!

I have implemented a similar thing in SimpleITK:

It is quite nice in C++, to easily be able to add a lambda function in nearly the same way as what has been done in Python.

I think we can add a similar feature to ITK in 5.2.

2 Likes

Here is an initial draft:

The original command callbacks had a signature of:

void f(const Object * caller, const EventObject & event)

With C++ lambdas, these are not really necessary, as those values can be specified in captures instead.

Here is the little test case of what’s implemented:

   itk::Object::Pointer o = itk::Object::New();

   int cnt = 0;
   o->AddObserver(itk::AnyEvent(), [&cnt](const itk::EventObject &) { ++cnt; });

I think I am in favor of removing all the arguments for the std::function/lambda use cases. What do you think?

1 Like