【发布时间】:2011-12-06 13:55:38
【问题描述】:
我在重载函数以通过 const 引用获取值时遇到问题,或者,如果它是一个右值,一个右值引用。问题是我的非常量左值绑定到函数的右值版本。我在 VC2010 中这样做。
#include <iostream>
#include <vector>
using namespace std;
template <class T>
void foo(const T& t)
{cout << "void foo(const T&)" << endl;}
template <class T>
void foo(T&& t)
{cout << "void foo(T&&)" << endl;}
int main()
{
vector<int> x;
foo(x); // void foo(T&&) ?????
foo(vector<int>()); // void foo(T&&)
}
优先级似乎是推断 foo(x) 为
foo< vector<int> & >(vector<int>& && t)
而不是
foo< vector<int> >(const vector<int>& t)
我尝试将右值引用版本替换为
void foo(typename remove_reference<T>::type&& t)
但这只会导致所有内容都解析为 const-lvalue 参考版本。
如何防止这种行为?为什么这是默认值 - 考虑到允许修改右值引用,这似乎很危险,这给我留下了一个意外修改的局部变量。
编辑:刚刚添加了函数的非模板版本,它们按预期工作。使函数成为模板会更改重载解析规则?那……真是令人沮丧!
void bar(const vector<int>& t)
{cout << "void bar(const vector<int>&)" << endl;}
void bar(vector<int>&& t)
{cout << "void bar(vector<int>&&)" << endl;}
bar(x); // void bar(const vector<int>&)
bar(vector<int>()); // void bar(vector<int>&&)
【问题讨论】:
-
当你使
xconst 时会发生什么?在另一个调用 foo 之后使用x会发生什么? -
可以安排推导的 T&& 只绑定到右值。见ideone.com/XSBifq。但我不会推荐这个。公认的答案,即不要像这样使用重载,是正确的方法。
标签: c++ templates metaprogramming rvalue-reference