在C ++ 0x中完美转发使reference

编程入门 行业动态 更新时间:2024-10-24 09:21:16
本文介绍了在C ++ 0x中完美转发使reference_wrapper不推荐使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

照常,代码第一:

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

在C ++ 98中,通过模板函数完成向前参数的一种很好的方法。因此,C ++的古茹发明了ref和cref来实现这个目标。

In C++ 98, we don't have a nice way to pefect forward parameters through template functions. So the C++ gurus invented ref and cref to achieve that aim.

现在我们已经有了r值引用和完美的转发,这意味着ref和cref like应该被弃用?

Now that we have had r-value reference and perfect forwarding, does it mean that ref and cref and the like should be deprecated?

推荐答案

引用包装器仍然有用。这是关于存储的东西的情况。例如,使用引用包装器可以使std :: make_tuple和std :: thread创建引用一些参数而不是复制它们的对象:

Reference wrappers are still useful. This is the case when it's about storing things. For example, with reference wrappers you can make std::make_tuple and std::thread create objects which refer to some 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' 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(); }

请记住,

make_tuple(std::ref(i)) // yields a tuple<int&> make_tuple( i ) // yields a tuple<int>

干杯! s

Cheers! s

更多推荐

在C ++ 0x中完美转发使reference

本文发布于:2023-08-04 17:32:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298253.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:完美   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!