省略std::bind中的std::占位符

omit std::placeholders in std::bind

本文关键字:std 占位符 中的 bind 省略      更新时间:2023-10-16

要创建std::function,我要做的是:-

std::function<void(int,int,int)> f =
    std::bind(&B::fb,this,
        std::placeholders::_1,
        std::placeholders::_2,
        std::placeholders::_3
    );  
void B::fb(int x,int k,int j){} //example

显然,CCD_ 2接收三个参数
为了增加可读性&可维护性,我希望我可以称之为:-

std::function<void(int,int,int)> f=std::bind(&B::fb,this);  //omit _1 _2 _3

问题
C++中有什么功能可以省略占位符吗
它应该调用_1_2。。。,订单中自动。

我在谷歌上搜索了";省略占位符c++";但没有找到任何线索。

您可以创建函数助手(那些是C++14):

template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(C* c, Ret (C::*m)(Ts...))
{
    return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}
template <class C, typename Ret, typename ... Ts>
std::function<Ret(Ts...)> bind_this(const C* c, Ret (C::*m)(Ts...) const)
{
    return [=](auto&&... args) { return (c->*m)(std::forward<decltype(args)>(args)...); };
}

然后只写

std::function<void(int, int, int)> f = bind_this(this, &B::fb);