7

Chciałbym mieć funkcję BindFirst, która wiąże pierwszy argument funkcji bez konieczności jawnego poznania/podania arytmetycznego funkcji za pomocą std :: placeholders. Chciałbym, żeby kod klienta wyglądał tak.wiążę pierwszy argument funkcji bez znajomości jego wartości

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

Jakieś pomysły, w jaki sposób można wdrożyć BindFirst?

Odpowiedz

8

w 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

w 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

mogę wiedzieć dlaczego 'std :: decay' jest używany? – billz

+0

@billz Ponieważ tutaj chcemy przechowywać kopie (prawdopodobnie przeniesione) argumentów przekazywanych do 'BindFirst'. Na pewno nie chcesz przechowywać referencji, ani ich konstytutywność/niestabilność jest tutaj interesująca. Powiedz, dla 'T && = int &&' chcesz zachować 'int' –

Powiązane problemy