Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

omit std::placeholders in std::bind

To create std::function, here is what I do:-

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

It is obvious that B::fb receive three parameters.
To increase readability & maintainablity, I wish I could call this instead :-

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

Question
Are there any features in C++ that enable omitting the placeholders?
It should call _1,_2, ..., in orders automatically.

I have googled "omit placeholders c++" but not find any clue.

like image 796
javaLover Avatar asked Feb 07 '23 11:02

javaLover


1 Answers

You may create functions helper (those ones are 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)...); };
}

and then just write

std::function<void(int, int, int)> f = bind_this(this, &B::fb);
like image 92
Jarod42 Avatar answered Feb 24 '23 10:02

Jarod42