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

前提是你 提交于 2019-12-02 13:53:48

问题


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"


回答1:


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(); });



回答2:


You could use std::bind (see http://en.cppreference.com/w/cpp/utility/functional/bind)

dds::sub::cond::ReadCondition rc(*mp_reader,
                                 dds::sub::status::DataState::any(),
                                 std::bind(&MyClass::do_stuff, this));

See also How to directly bind a member function to an std::function in Visual Studio 11?



来源:https://stackoverflow.com/questions/49137831/c-how-do-you-pass-a-member-function-into-a-functor-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!