绑定函数的第一个参数,但不知道其arity

问题描述 投票:8回答:1

我希望有一个函数BindFirst绑定一个函数的第一个参数,而我不必通过使用std :: placeholders明确地知道/陈述该函数的含义。我希望客户端代码看起来像这样。

#include <functional>
#include <iostream>

void print2(int a, int b)
{
    std::cout << a << std::endl;
    std::cout << b << std::endl;
}

void print3(int a, int b, int c)
{
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
}

int main()
{ 
    auto f = BindFirst(print2, 1); // std::bind(print2, 1, std::placeholders::_1);
    auto g = BindFirst(print3, 1); // std::bind(print3, 1, std::placeholders::_1, std::placeholders::_2);
    f(2);
    g(2,3);
}

有什么想法可以实现BindFirst

c++ c++11 functional-programming c++14 bind
1个回答
10
投票

在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

在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

© www.soinside.com 2019 - 2024. All rights reserved.