Search code examples
c++functormember-functions

C++ How do you pass a member function into a functor parameter?


I am using TRI DDS - here is the prototype for the function I am trying to call:

template<typename T , typename Functor >
dds::sub::cond::ReadCondition::ReadCondition  (
  const dds::sub::DataReader< T > &  reader,  
  const dds::sub::status::DataState &  status,  
  const Functor &  handler  
)

So I have a class that looks a bit like this (with load of irrelevant stuff omitted):

MyClass test{
public:
    test(){... mp_reader = ...}; // not complete

    start_reader()
    {
        dds::sub::cond::ReadCondition rc(*mp_reader,
                                         dds::sub::status::DataState::any(),
                                         do_stuff());  // This does not work
    }

    void do_stuff() {...}
private:
    dds::sub::DataReader* mp_reader;

}

So I just tried to pass in the function do_stuff().. I know this won't work, but I am not sure what to put in here in place of the const & functor parameter. Can I pass a member function in? - how do I specify the instance of the class?

I tried putting a lambda in there and it worked - but I can't access mp_reader in the lambda because it is not in the scope of the lambda. But anyway I don't really want to use a lambda I really want to use a function (so, eventually I might be able to pass in an external one).

Please see here for the RTI DDS function. Here is what it says about the functor type:

"Any type whose instances that can be called with a no-argument function call (i.e. f(), if f is an instance of Functor). Examples are functions, types that override the operator(), and lambdas <<C++11>>. The return type has to be void"


Solution

  • You can use a lambda function with a capture.

    dds::sub::cond::ReadCondition rc(*mp_reader,
                                     dds::sub::status::DataState::any(),
                                     [this](){ this->do_stuff(); });