【问题标题】:bind first argument of function without knowing its arity在不知道其元数的情况下绑定函数的第一个参数
【发布时间】:2016-02-16 21:10:22
【问题描述】:

我想要一个函数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】:

    :

    #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

    :

    #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

    【讨论】:

    • 我能知道为什么使用std::decay吗?
    • @billz 因为在这里我们想要存储传递给BindFirst 的参数的副本(可能是移动构造的)。您当然不想存储引用,它们的 constness/volatile 在这里也不符合您的兴趣。比如说,对于T&amp;&amp;=int&amp;&amp;,你想存储int
    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 2011-11-14
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多