Following on from this question
I now have the following template class (partially formed here for brevity) DDS_Interface.hpp
:
MyClass DDS_Interface{
public:
DDS_Interface(){... mp_reader = ...}; // not complete
template <typename Functor>
void start_reader(const Functor & handler) // <-- HERE
{
dds::sub::cond::ReadCondition rc(*mp_reader,
dds::sub::status::DataState::any(),
[ &handler ]()
{
// do stuff (populate sample)
handler(sample.data()); // <-- HERE
}; );
}
private:
dds::sub::DataReader* mp_reader;
}
Then I have some code in main.cpp:
void handler(MyDataType data)
{
printf("cols: %d, rows: %d\r\n", data.cols(), data.rows());
}
int main()
{
DDS_Interface<MyDataType> dds();
dds.start_reader(handler); // <-- HERE
}
Added some HERE
comments to point out key parts of the code. Now this appears to work fine (I am new-ish to lambda and functors so if you see anything silly in this code - please comment!)
However, now that I have managed to get this bit to work - the main thing here is that I am passing a functor into dds.start_reader(...)
- I want to pass a member function (or pointer to one).
So now I change main.cpp to this:
class Test
{
public:
Test() : m_dds() {}; // init m_dds
void handler(MyDataType data)
{
printf("cols: %d, rows: %d\r\n", data.cols(), data.rows());
}
void start()
{
m_dds.start_reader(this->handler); // this does not work
}
private:
DDS_Interface<MyDataType> m_dds;
}
So you can see that instead of passing a basic function-pointer I am trying to pass a member function pointer.
I know that the signature for a member function pointer is something like Test::*handler
. But I want start_reader
to take a member function of from any class, so that is why I have (now probably wrongly):
template <typename Functor>
void start_reader(const Functor & handler)
I have read quite a lot about this, but I still can't quite figure out how to resolve this part... so my question is sort of "how do I get a square peg into a round hole"? - i.e. how do I pass any member function into start_reader()
effectively as a call-back. I can change the start_reader signature to pass the class instance (or anything else) as required...
note: I am using MSVC 2012 which is mostly c++11 compliant (but not fully). I don't want to use boost, but I think MSVC 2012 supports things like bind and std::function if that helps?!