Perfect forwarding with multiple passes on input arguments

Consider the following function accept, which takes a "universal reference" type Tand translates it into a function object parse<T>()with overloading for lvalues ​​and one for rvalues:

template<class T>
void accept(T&& arg)
{
    parse<T>()(std::forward<T>(arg), 0); // copy or move, depending on rvaluedness of arg
}

template<class T>
class parse
{
    // parse will modify a local copy or move of its input parameter
    void operator()(T const& arg, int n) const { /* optimized for lvalues */ }
    void operator()(T&& arg)    , int n) const { /* optimized for rvalues */ }
};

Since perfect forwarding leaves the original object in a valid, but undefined state, it is impossible to perfectly redirect again within the same area. Below is my attempt to have as few instances as possible in a hypothetical split()function that takes int, representing the number of passes that must be made over the input:

template<class T>
void split(T&& arg, int n)
{
    for (auto i = 0; i < n - 1; ++i)
        parse<T>()(arg , i);                 // copy n-1 times
    parse<T>()(std::forward<T>(arg), n - 1); // possibly move the n-th time
}

: ? , ?

+4
1

: - ?

, ( ), . () . , , "" , rvalue-reference, . N1377:

rvalue rvalue, lvalues ​​ . :

struct A {};

void h(const A&);
void h(A&&);

void g(const A&);
void g(A&&);

void f(A&& a)
{
    g(a);  // calls g(const A&)
    h(a);  // calls h(const A&)
}

rvalue "a" f(), , a lvalue. , g() h() const A & (lvalue) . "a" rvalue f : " " g(), , , "a", "a" h().

, h(a) , :

    h(std::move(a));  // calls h(A&&);

Casey , lvalues:

#include  <utility>
#include  <type_traits>

template<class T>
class parse
{
    static_assert(!std::is_lvalue_reference<T>::value,
                               "parse: T can not be an lvalue-reference type");
public:
    // parse will modify a local copy or move of its input parameter
    void operator()(T const& arg, int n) const { /* optimized for lvalues */ }
    void operator()(T&& arg     , int n) const { /* optimized for rvalues */ }
};

template<class T>
void split(T&& arg, int n)
{
    typedef typename std::decay<T>::type Td;
    for (auto i = 0; i < n - 1; ++i)
        parse<Td>()(arg , i);                 // copy n-1 times
    parse<Td>()(std::forward<T>(arg), n - 1); // possibly move the n-th time
}

, , parse<T> , std::decay. static_assert, , . static_assert , . static_assert .

. , parse lvalue, , :

template<class T>
class parse<T&>
{
public:
    // parse will modify a local copy or move of its input parameter
    void operator()(T const& arg, int n) const { /* optimized for lvalues */ }
};

decay:

template<class T>
void split(T&& arg, int n)
{
    for (auto i = 0; i < n - 1; ++i)
        parse<T>()(arg , i);                 // copy n-1 times
    parse<T>()(std::forward<T>(arg), n - 1); // possibly move the n-th time
}

parse<T&>.

+8

All Articles