将移动语义隐藏在单个函数后面

Hiding move semantics behind single function

本文关键字:函数 单个 移动 语义 隐藏      更新时间:2023-10-16

例如,我有一个可以处理const T &T &&值的函数:

template <typename T>
/* ... */ foo(const T &) {
std::cout << "const T & as arg" << std::endl;
}
template <typename T>
/* ... */ foo(T &&) {
std::cout << "T && as arg" << std::endl;
}

有没有一种方法可以让我编写一个单独的函数,自动处理这两种类型?如:

template <typename T>
/* ... */ bar(T t) {
    foo(t);
}

因此:

T a;
bar(a); // Handles as const T &
T b;
bar(std::move(b)); // Handles as T &&

谢谢!

您可以使用引用折叠和std::forward将参数转发到foo函数:

template <typename T>
/* ... */ bar(T&& t) {
    foo(std::forward<T>(t));
}

请注意,您的foo函数将接受右值、常值和非常值。举个例子,给定:

const int x = 456;
int y = 123;

然后:

foo(123);   // foo(T&&)
foo(x);     // foo(const T&)
foo(y);     // foo(T&&)

现场演示