我应该什么时候使用向前和移动? [英] When should I use forward and move?
问题描述
我有一个操作一个向量的代码:
template< typename T&
void doVector(vector< T& v,T&& amp; value){
// ....
v.push_back(value);
// ...
}
对于正常 push_back
,我需要使用 forward(value)
, move(value)
或者只是 value
(根据新的C ++ 11)?
例如,
v.push_back(forward< T>(value));
当第二个参数是 ,因为 T&&&
会变成 X&
c $ c> T 需要 X&
,这又意味着 std :: vector< T>
将变成 std :: vector< X>的第一个参数不匹配的
std :: vector< X& &
。因此,这是一个错误。
我将使用两个模板参数:
template< typename T,typename V>
void doVector(vector< T& v,V&&& amp; value)
{
v.emplace_back(std :: forward< V&
}
由于 V
与 T
不同的类型,因此 emplace_back
会使更多感,因为它不仅解决了问题,它使代码更通用。 : - )
现在下一个改进:因为我们使用 emplace_back
c $ c> T 从参数 value
(可能使用构造函数),我们可以利用这个事实,并使其变化函数: p>
模板< typename T,typename ... V>
void doVector(vector< T>& v,V& ... value)
{
v.emplace_back(std :: forward< V& 。);
}
这是更通用的,因为你可以使用它:
struct point
{
point(int,int){}
};
std :: vector< point> pts;
doVector(pts,1,2);
std :: vector< int> ints;
doVector(ints,10);
希望有帮助。
I have a code that operates on a vector:
template<typename T>
void doVector(vector<T>& v, T&& value) {
//....
v.push_back(value);
//...
}
For normal push_back
, do I need to use forward(value)
, move(value)
or just value
(according to new C++11) ? and how do they impact the performance?
For example,
v.push_back(forward<T>(value));
The current code will not compile when the second argument is lvalue because T&&
will turn out to be X&
which means T
needs to be X&
which in turn means std::vector<T>
will become std::vector<X&>
which will NOT match the first argument which is std::vector<X> &
. Hence, it is an error.
I would use two template parameters:
template<typename T, typename V>
void doVector(vector<T> & v, V && value)
{
v.emplace_back(std::forward<V>(value));
}
Since V
could a different type from T
, so emplace_back
makes more sense, because not only it solves the problem, it makes the code more generic. :-)
Now the next improvement : since we're using emplace_back
which creates the object of type T
from argument value
(possibly using constructor), we could take advantage of this fact, and make it variadic function:
template<typename T, typename ...V>
void doVector(vector<T> & v, V && ... value)
{
v.emplace_back(std::forward<V>(value)...);
}
That is even more generic, as you could use it as:
struct point
{
point(int, int) {}
};
std::vector<point> pts;
doVector(pts, 1, 2);
std::vector<int> ints;
doVector(ints, 10);
Hope that helps.
这篇关于我应该什么时候使用向前和移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!