考虑一个函数模板需要转发一个参数同时保持它的左值性以防它是一个非常量左值的情况,但它本身与参数的实际情况无关,如下所示:
template <typename T>
void target(T&) {
cout << "non-const lvalue";
}
template <typename T>
void target(const T&) {
cout << "const lvalue or rvalue";
}
template <typename T>
void forward(T& x) {
target(x);
}
当x
是一个右值,而不是被推T
导出为一个常量类型,它给出了一个错误:
int x = 0;
const int y = 0;
forward(x); // T = int
forward(y); // T = const int
forward(0); // Hopefully, T = const int, but actually an error
forward<const int>(0); // Works, T = const int
似乎forward
为了处理右值(不调用显式模板参数)需要有一个forward(const T&)
重载,即使它的主体将是一个完全相同的副本。
有没有办法避免这种重复?