2015-11-15 28 views
7

Mi piacerebbe avere una funzione BindFirst che leghi il primo argomento di una funzione senza che io debba conoscere/dichiarare esplicitamente l'arità della funzione usando std :: segnaposti. Mi piacerebbe che il codice client assomigliasse a qualcosa del genere.vincola il primo argomento della funzione senza conoscere la sua appartenenza

#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); 
} 

Qualche idea su come è possibile implementare BindFirst?

risposta

8

In 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

In 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

posso sapere il motivo per cui 'std :: decay' è Usato? – billz

+0

@billz Perché qui vogliamo archiviare le copie (eventualmente spostate) degli argomenti passati a 'BindFirst'. Certamente non vuoi memorizzare riferimenti, né la loro costanza/volatilità è di tuo interesse qui. Dì, per 'T && = int && 'vuoi memorizzare' int' –