C 接收const lvalue和rvalue参考参数,而无需过载


void f(const std::vector<int>& v)  //#1
{
    std::vector<int> a(v);
    ...
}
void f(std::vector<int>&& v)       //#2
{
    std::vector<int> a(std::move(v));
    ...
}

是否有某种方法可以将#1和#2编写在一个函数中,而不会超负荷但实现相同的效果?我的意思是,如果参数是lvalue,则使用复制构造函数,如果参数为rvalue,则使用移动构造函数。

您可以看到,如果有多个参数,我需要编写2^n个过载。

您不需要两者!使用转发您可以很容易地写:

template < typename T >
void f(T&& t)
{
  std::vector<int> v(std::forward<T>(t));
}

然后所有这些以下电话都会起作用:

std::vector<int> a = { 1, 2, 3 };
f(std::move(a));
f(a);
const std::vector<int> b = { 1, 2, 3 };
f(b);

最新更新