【发布时间】:2011-01-02 13:23:11
【问题描述】:
考虑以下情况:函数模板需要转发参数同时保持它的左值性,以防它是非 const 左值,但它本身与参数实际是什么无关,如下所示:
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&) 重载,即使它的主体是完全重复的。
有什么办法可以避免这种重复吗?
【问题讨论】:
-
如果你像这样超载左值,你应该被枪杀。
标签: c++ templates reference type-inference rvalue