c++ - Does perfect forwarding in C++0x make reference_wrapper deprecated? -
as usual, code first:
#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 = 0; g1(f, ref(i)); // old way, ugly way g2(f, i); // new way, elegant way }
in c++ 98, don't have nice way pefect forward parameters through template functions. c++ gurus invented ref , cref achieve aim.
now have had r-value reference , perfect forwarding, mean ref , cref , should deprecated?
reference wrappers still useful. case when it's storing things. example, reference wrappers can make std::make_tuple , std::thread create objects refer argument instead of copying them:
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' new thread // supposed invoke ptr->run(); } ... }; ... void foo(const int&); int main() { thread t (foo, 42); // 42 copied , foo invoked t.join() // reference copy int = 23; thread z (foo, std::cref(i)); // foo reference z.join(); }
keep in mind that
make_tuple(std::ref(i)) // yields tuple<int&> make_tuple( ) // yields tuple<int>
cheers! s
Comments
Post a Comment