bind first argument of function without knowing its arity

北战南征 提交于 2019-12-03 12:50:47

In C++11:

#include <type_traits>
#include <utility>

template <typename F, typename T>
struct binder
{
    F f; T t;
    template <typename... Args>
    auto operator()(Args&&... args) const
        -> decltype(f(t, std::forward<Args>(args)...))
    {
        return f(t, std::forward<Args>(args)...);
    }
};

template <typename F, typename T>
binder<typename std::decay<F>::type
     , typename std::decay<T>::type> BindFirst(F&& f, T&& t)
{
    return { std::forward<F>(f), std::forward<T>(t) };
}

DEMO 1

In C++14:

#include <utility>

template <typename F, typename T>
auto BindFirst(F&& f, T&& t)
{
    return [f = std::forward<F>(f), t = std::forward<T>(t)]
           (auto&&... args)
           { return f(t, std::forward<decltype(args)>(args)...); };
}

DEMO 2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!