Permalink
Browse files

Use Callable and invoke()

  • Loading branch information...
jlblancoc committed Aug 5, 2018
1 parent 548b940 commit 44458408c006238e633d2cf1b332019ec99e9224
Showing with 36 additions and 17 deletions.
  1. +4 −5 libs/comms/include/mrpt/comms/nodelets.h
  2. +32 −12 samples/comms_nodelets_example/NodeletsTest_impl.cpp
@@ -58,20 +58,19 @@ class Topic : public std::enable_shared_from_this<Topic>

~Topic();

template <typename ARG>
Subscriber::Ptr createSubscriber(
typename std::function<void(const ARG&)>&& func)
template <typename ARG, typename Callable>
Subscriber::Ptr createSubscriber(Callable&& func)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_subs.emplace_back();
auto it = m_subs.end();
it--;
auto capturedShared = shared_from_this();
auto newNode = Subscriber::create(
[=](const std::any& anyArg) {
[func{std::forward<Callable>(func)}](const std::any& anyArg) {
try
{
func(std::any_cast<const ARG&>(anyArg));
std::invoke(func, std::any_cast<const ARG&>(anyArg));
}
catch (std::bad_any_cast&)
{
@@ -64,6 +64,14 @@ void onNewMsg(const mrpt::poses::CPose3D& p)
#endif
}

void onNewMsg2(int idx, const mrpt::poses::CPose3D& p)
{
#ifdef NODELETS_TEST_VERBOSE
std::cout << "onNewMsg2: idx=" << idx << " rx CPose3D" << p.asString()
<< std::endl;
#endif
}

void thread_subscriber()
{
using namespace mrpt::comms;
@@ -80,22 +88,34 @@ void thread_subscriber()
#endif

// Create a subscriber with a lambda:
Subscriber::Ptr sub1 = dir->getTopic("/robot/odom")
->createSubscriber(
std::function<void(const mrpt::poses::CPose3D&)>(
[](const mrpt::poses::CPose3D& p_rx) -> void {
Subscriber::Ptr sub1 =
dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(
std::function<void(const mrpt::poses::CPose3D&)>(
[](const mrpt::poses::CPose3D& p_rx) -> void {
#ifdef NODELETS_TEST_VERBOSE
std::cout << "sub1: rx CPose3D"
<< p_rx.asString() << std::endl;
std::cout << "sub1: rx CPose3D" << p_rx.asString()
<< std::endl;
#endif
nodelets_test_passed_ok = (p_rx == p_tx);
}));
nodelets_test_passed_ok = (p_rx == p_tx);
}));

// Create a subscriber with a regular function:
// Create a subscriber with a regular function via std::function:
auto sub2 = dir->getTopic("/robot/odom")
->createSubscriber(
std::function<void(const mrpt::poses::CPose3D&)>(
&onNewMsg));
->createSubscriber<mrpt::poses::CPose3D>(
std::function<void(const mrpt::poses::CPose3D&)>(
&onNewMsg));

// Create a subscriber with a regular function:
auto sub3 = dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(&onNewMsg);

// Create a subscriber with std::bind:
using namespace std::placeholders;
auto sub4 = dir->getTopic("/robot/odom")
->createSubscriber<mrpt::poses::CPose3D>(std::bind(
onNewMsg2, 123 /*fixed 1st argument*/,
_1 /* 2nd arg is the subscribed data */));

// wait for messages to arrive.
// The nodelet is up and live until "sub" gets out of scope.

0 comments on commit 4445840

Please sign in to comment.