2015-11-15 34 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' –