C++ 0x中的完美转发是否会使reference_wrapper弃用?

xml*_*lmx 7 c++ c++11

像往常一样,代码优先:

#include <functional>

using namespace std;
using namespace std::tr1;

void f(int& r) { r++; }

template<class F, class P> void g1(F f, P t) { f(t); }
template<class F, class P> void g2(F f, P&& t) { f(forward<P>(t)); }

int main()
{
    int i = 0;

    g1(f, ref(i)); // old way, ugly way
    g2(f, i); // new way, elegant way
}
Run Code Online (Sandbox Code Playgroud)

在C++ 98中,我们没有一种通过模板函数来完善前向参数的好方法.所以C++大师发明了ref和cref来实现这个目标.

现在我们已经有了r值参考和完美转发,是否应该弃用ref和cref等?

sel*_*tze 3

参考包装仍然有用。当涉及到存储东西时就是这种情况。例如,使用引用包装器,您可以使 std::make_tuple 和 std::thread 创建引用某些参数的对象,而不是复制它们:

class abstract_job
{
public:
    virtual ~abstract_job() {}
    virtual void run() = 0;
};

class thread
{
public:
    template<class Fun, class... Args>
    thread(Fun&& f, Args&&... args)
    {
        typedef typename decay<Fun>::type fun_type;
        typedef decltype( make_tuple(forward<Args>(args)...) ) tuple_type;
        unique_ptr<abstract_job> ptr (new my_job<fun_type,tuple_type>(
            forward<Fun>(fun),
            make_tuple(forward<Args>(args)...)
        ));
        // somehow pass pointer 'ptr' to the new thread
        // which is supposed to invoke ptr->run();
    }
    ...
};

...

void foo(const int&);

int main()
{
   thread t (foo, 42); // 42 is copied and foo is invoked 
   t.join()            // with a reference to this copy
   int i = 23;
   thread z (foo, std::cref(i)); // foo will get a reference to i
   z.join();
}
Run Code Online (Sandbox Code Playgroud)

请记住

make_tuple(std::ref(i))  // yields a tuple<int&>
make_tuple(         i )  // yields a tuple<int>
Run Code Online (Sandbox Code Playgroud)

干杯! s