How to store universal links

I need to store generic links inside a class (I'm sure reference values ​​will iterate over the class). Is there a canonical way to do this?

Here is a minimal example of what I came up with. This seems to work, but I'm not sure if I understood correctly.

template <typename F, typename X>
struct binder
{
    template <typename G, typename Y>
    binder(G&& g, Y&& y) : f(std::forward<G>(g)), x(std::forward<Y>(y)) {}

    void operator()() { f(std::forward<X>(x)); }

    F&& f;
    X&& x;
};

template <typename F, typename X>
binder<F&&, X&&> bind(F&& f, X&& x)
{
    return binder<F&&, X&&>(std::forward<F>(f), std::forward<X>(x));
}

void test()
{
    int i = 1;
    const int j = 2;
    auto f = [](int){};

    bind(f, i)();   // X&& is int&
    bind(f, j)();   // X&& is const int&
    bind(f, 3)();   // X&& is int&&
}

Am I reasoning correctly or will this lead to subtle errors? Also, is there a better (i.e., more succinct) way to write constructor? binder(F&& f, X&& x)will not work, since these are r-value references, thereby forbidding binder(f, i).

+5
source share
2 answers

" ", , rvalue lvalue. " " - , .

:

template <typename F, typename X>
binder<F&&, X&&> bind(F&& f, X&& x)

binder , rvalue-, ( lvalue, rvalue bind). , &&, , - .

, binder bind ( ), :

template <typename F, typename X>
struct binder
{
    binder(F g, X y) : f(std::forward<F>(g)), x(std::forward<X>(y)) {}

    void operator()() { f(std::forward<X>(x)); }

    F f;
    X x;
};

F X , F&& X&&, lvalue ( && ), 're reval ( && !)

binder , , bind :

template <typename F, typename X>
binder<F, X> bind(F&& f, X&& x)
{
    return binder<F, X>(std::forward<F>(f), std::forward<X>(x));
}

binder lvalue, ( ), binder &&, lvalue, rvalue .

, , rvalue. lvalue, , , , lvalues ​​ rvalues ​​ operator(). , F& X& ( , , F X)

, :

template <typename F, typename X>
struct binder
{
    binder(F& g, X& y) : f(g), x(y) { }

    void operator()() { f(std::forward<X>(x)); }

    F& f;
    X& x;
};

template <typename F, typename X>
binder<F, X> bind(F&& f, X&& x)
{
    return binder<F, X>(f, x);
}

F X std::forward<X>(x), , .

, , () :

bind(f, i)();   // X is int&, X&& is int&
bind(f, j)();   // X is const int&, X&& is const int&
bind(f, 3)();   // X is int, X&& is int&&
+4

binder(F&& f, X&& x) .

F X ( , binder<F&&, X&&>), F X , .

, ( , ).

+1

All Articles