0

I have code as foolows

template <typename T, typename P>
Nats::MessageCallback registerNatsCallback(P* p)
{
    using std::placeholders::_1;
    using std::placeholders::_2;
    using std::placeholders::_3;
    return std::bind(T, p, _1, _2, _3);
}

I want to use this i this way:

nc.subscribe("Test_1", registerNatsCallback<&App::natsHandler1>(this));

Unfortenly i ended up with compiler error (gcc)

In file included from ..\NATS_CLIENT\main.cpp:2:0:
..\NATS_CLIENT\app.h: In member function 'Nats::MessageCallback
App::registerNatsCallback(P*)':
..\NATS_CLIENT\app.h:28:27: error: expected primary-expression before ',' token
     return std::bind(T, p, _1, _2, _3);

I think that this error has connection with this link, but I didn't see how I can apply 'template' in my situation. I don't have to much experience in templates...

2 Answers2

0

You try to pass the function by type only, and it doesn't work. Instead you should pass the method as a pointer, like this:

template <typename T, typename P>
auto registerNatsCallback(T && t, P && p)
{
    using std::placeholders::_1;
    using std::placeholders::_2;
    using std::placeholders::_3;
    return std::bind(std::forward<T>(t), std::forward<P>(p), _1, _2, _3);
}

Notice the use of std::forward() that might improve your implementation.


A full example:

template <typename T, typename P>
auto registerNatsCallback(T && t, P && p)
{
    using std::placeholders::_1;
    using std::placeholders::_2;
    using std::placeholders::_3;
    return std::bind(std::forward<T>(t), std::forward<P>(p), _1, _2, _3);
}

void sample(const char * msg, int a, int b, int c)
{
    std::cout << msg << " " << a << " " << b << " " << c;
}

int main()
{
    auto callback = registerNatsCallback(sample, "hello");
    callback(1,2,3);
}
Daniel Trugman
  • 8,186
  • 20
  • 41
0

Don't use std::bind, it's archaic, inefficient and cumbersome.

Use a lambda instead:

nc.subscribe("Test_1", [this](auto& a, auto& b, auto& c) { return natsHandler1(a, b, c); });
rustyx
  • 80,671
  • 25
  • 200
  • 267