简体   繁体   English

C ++模板“预期在主表达式之前”

[英]C++ templates “expected primary-expression before”

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) 不幸的是,我最终遇到编译器错误(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... 我在模板方面没有太多经验...

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. 注意使用std::forward()可能会改善您的实现。


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

Don't use std::bind , it's archaic, inefficient and cumbersome . 不要使用std::bind ,它是过时的,低效的和繁琐的

Use a lambda instead: 改用lambda

nc.subscribe("Test_1", [this](auto& a, auto& b, auto& c) { return natsHandler1(a, b, c); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM