2015-11-15 30 views
7

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

#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

回答

8

在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

+0

我可以知道为什么'的std :: decay'是用过的? – billz

+0

@billz因为这里我们想存储传递给'BindFirst'的参数的副本(可能是移动构造的)。你当然不想存储引用,他们的常量/不稳定性在这里是你感兴趣的。说,对于'T && = int &&'你想存储'int' –