问题描述
照常,代码第一:
#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_wrapper不推荐使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!