Reputation: 6425
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 & maintainability, 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.
Upvotes: 5
Views: 1578
Reputation: 217265
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);
Upvotes: 9