13

Is there a way to partially bind the first/last n arguments of a callable object (e.g. function) without explicitly specifying the rest of the arguments?

std::bind() seems to require that all the arguments are be bound, those that are to be left should be bound to std::placeholders::_1,_2,_3 etc.

Is it possible to write a bind_first()/bind_last() for partial binding starting from the first/last argument and that automagically inserts the placeholders for any remaining unbound arguments in their original order in their the original position?

4

3 回答 3

6

Boost 和标准库都不会bind自动填空。如果你有一个下雨的晚上,你可以自己写一个这样的小工具;这是一个仅用于普通函数的尾随参数的示例:

#include <tuple>
#include <type_traits>
#include <utility>

template <typename F, typename ...Args> struct trailing_binder;

template <typename R, typename ...Frgs, typename ...Args>
struct trailing_binder<R(Frgs...), Args...>
{
    template <typename ...Brgs>
    trailing_binder(R (*f)(Frgs...), Brgs &&... brgs)
    : the_function(f)
    , the_args(std::forward<Brgs>(brgs)...)
    { }

    template <unsigned int ...I> struct intlist {};

    template <typename ...Brgs>
    typename std::enable_if<sizeof...(Brgs) + sizeof...(Args) == sizeof...(Frgs), R>::type
    operator()(Brgs &&... brgs)
    {
        return unwrap(std::integral_constant<bool, 0 == sizeof...(Args)>(),
                      intlist<>(),
                      std::forward<Brgs>(brgs)...);
    }

private:
    template <unsigned int ...I, typename ...Brgs>
    R unwrap(std::false_type, intlist<I...>, Brgs &&... brgs)
    {
        return unwrap(std::integral_constant<bool, sizeof...(I) + 1 == sizeof...(Args)>(),
                      intlist<I..., sizeof...(I)>(),
                      std::forward<Brgs>(brgs)...);
    }

    template <unsigned int ...I, typename ...Brgs>
    R unwrap(std::true_type, intlist<I...>, Brgs &&... brgs)
    {
        return the_function(std::get<I>(the_args)..., std::forward<Brgs>(brgs)...);
    }

    R (*the_function)(Frgs...);
    std::tuple<Args...> the_args;
};

template <typename R, typename ...Args, typename ...Frgs>
trailing_binder<R(Frgs...), Args...> trailing_bind(R (*f)(Frgs...), Args &&... args)
{
    return trailing_binder<R(Frgs...), typename std::decay<Args>::type...>(f, std::forward<Args>(args)...);
}

用法:

int f(int a, int b, int c, int d) { return a + b + c + d; }

int main()
{
    auto b = trailing_bind(f, 1);
    return b(3, 8, 13);
}
于 2014-01-19T13:47:36.977 回答
0

受这个问题的启发,我从头开始编写了自己的预绑定。虽然它最终看起来与其他所有人都非常相似,但我保证它是原创的 :) - 称之为趋同进化。

不过它的味道略有不同。一方面,它转发给它的构造函数,但您可能更喜欢使用std::decay(它在某些方面更有意义,但我不喜欢std::ref到处写)。另外,我添加了对嵌套预绑定的支持,因此prebind(foo, prebind(GetRandomNumber))()prebind(foo)(GetRandomNumber()).

#include <tuple>
#include <type_traits>
using namespace std;

struct pb_tag {}; //use inheritance to mark prebinder structs

//result_of_t will be defined by default in c++1y
template<typename T > using result_of_t = typename result_of<T>::type;
template<typename T> using is_prebinder = is_base_of<pb_tag, typename remove_reference<T>::type >;

//ugly sequence generators for something different
template<int N, int ...S> struct seq : seq<N-1, N, S...> {};
template<int ...S> struct seq<0, S...> {typedef seq type;};

//these three functions are only for nested prebind. they map
//T t -> T t and Prebind<f, T...> -> f(T...)
template<typename T>
auto dispatchee(T&& t, false_type) -> decltype(forward<T>(t)){
    return forward<T>(t);
}

template<typename T>
auto dispatchee(T&& t, true_type) -> decltype(t())
{
    return t();
}

template<typename T>
auto expand(T&& t) -> decltype(dispatchee(forward<T>(t), is_prebinder<T>()))
{
    return dispatchee(forward<T>(t), is_prebinder<T>());
}

template<typename T> using expand_type = decltype(expand(declval<T>()));

//the functor which holds the closure in a tuple
template<typename f, typename ...ltypes>
struct prebinder : public pb_tag
{
    tuple<f, ltypes...> closure;
    typedef typename seq<sizeof...(ltypes)>::type sequence;
    prebinder(f F, ltypes... largs) : closure(F, largs...) {}

    template<int ...S, typename ...rtypes>
    result_of_t<f(expand_type<ltypes>..., rtypes...)>
    apply(seq<0, S...>, rtypes&& ... rargs){
        return (get<0>(closure))(expand(get<S>(closure))... , forward<rtypes>(rargs)...);
    }

    template<typename ...rtypes>
    result_of_t<f(expand_type<ltypes>..., rtypes...)>
    operator() (rtypes&& ... rargs){
        return apply(sequence(), forward<rtypes>(rargs)...);
    }
};

template<typename f, typename ...ltypes>
prebinder<f, ltypes...> prebind(f&& F, ltypes&&... largs)
{
    return prebinder<f, ltypes...>(forward<f>(F), forward<ltypes>(largs)...);
}

它也可以很容易地更改为 postbind。

用法如下:

int g(int a){ return 1 + a; }

int h(){ return 1; }

int i(int a, int b, int c, int d){
    return 1 + a + b + c + d;
}

int main()
{
    //completely bound
    auto a = prebind(g, 1);
    cout << a() << endl;

    //nested bind by reference
    auto b = prebind(g, a);
    cout << b() << endl;
    get<1>(a.closure) = 2;
    cout << b() << endl;

    //bind to prebinder
    auto c = prebind(b);
    cout << c() << endl;

    //nested bind of temp to temp
    auto d = prebind(prebind(g), prebind(h));
    cout << d() << endl;

    //and the one you wanted orginally
    auto e = prebind(i, 1, 1, 1);
    cout << e(1) << endl;

    return 0;
}
于 2014-01-19T13:41:22.680 回答
0

现在的建议是避免 Bind 并使用 lambda 包装对您的成员函数的调用。

https://releases.llvm.org/10.0.0/tools/clang/tools/extra/docs/clang-tidy/checks/modernize-avoid-bind.html

于 2020-11-19T11:19:37.223 回答