std::forward
背景
在 C++98 中,模板编程中存在一个重要问题:在泛型代码中,如何正确地将参数传递给目标函数,且不丢失参数的特性(如左值、常量性等)。由于 C++98 没有右值引用和现代值类别的概念,模板函数中的参数常常会被复制或丢失其原始属性,导致难以编写高效的泛型代码。
示例问题
考虑以下代码:
#include <iostream>
void process(int& x) {
std::cout << "Lvalue reference: " << x << std::endl;
}
void process(const int& x) {
std::cout << "Const lvalue reference: " << x << std::endl;
}
template <typename T>
void wrapper(T arg) {
process(arg); // 问题出在这里
}
我们尝试通过 wrapper
函数将参数传递给 process
:
int main() {
int