Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 绑定函数的第一个参数而不知道其算术性_C++_C++11_Functional Programming_C++14_Bind - Fatal编程技术网

C++ 绑定函数的第一个参数而不知道其算术性

C++ 绑定函数的第一个参数而不知道其算术性,c++,c++11,functional-programming,c++14,bind,C++,C++11,Functional Programming,C++14,Bind,我希望有一个函数BindFirst,它绑定函数的第一个参数,而不必使用std::占位符显式地知道/声明函数的arity。我希望客户端代码看起来像这样 #include <functional> #include <iostream> void print2(int a, int b) { std::cout << a << std::endl; std::cout << b << std::endl; }

我希望有一个函数
BindFirst
,它绑定函数的第一个参数,而不必使用std::占位符显式地知道/声明函数的arity。我希望客户端代码看起来像这样

#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);
}
#包括
#包括
无效打印2(内部a、内部b)
{
标准::coutIn:

#包括
#包括
模板
结构粘合剂
{
F;T;
模板
自动运算符()(Args&&…Args)常量
->decltype(f(t,std::forward

在:

#包括
模板
自动绑定优先(F&&F,T&&T)
{
返回[f=std::forward(f),t=std::forward(t)]
(自动和…参数)
{返回f(t,std::forward(args)…);};
}

我能知道为什么使用
std::decay
吗?@billz,因为我们想在这里存储副本(可能需要移动)传递给
BindFirst
的参数中的一个。您当然不想存储引用,它们的常量/波动性也不是您感兴趣的。例如,对于
t&&=int&
您想存储
int
#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) };
}
#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)...); };
}