我一直在尝试使用模板成员函数在我的类中设置一个值。我想使用通用引用,以便我可以接受正确类型的任何变体(例如T
,、、、、、、T&
)T&&
const T
const T&
const T&&
但是,与接受通用引用的自由函数不同,我的成员函数似乎只接受右值。
template <typename T>
class Foo{
public:
void memberURef(T&& t){
val = std::forward<T>(t);
}
private:
T val;
};
template <typename T>
void freeURef(T&& t){
}
int main() {
int lval = 1;
const int clval = 1;
freeURef(lval); // fine
freeURef(clval); // fine
Foo<int> foo;
foo.memberURef(2);
foo.memberURef(lval); //error: cannot bind 'int' lvalue to 'int&&'
foo.memberURef(clval); //error: no matching function for call to 'Foo<int>::memberURef(const int&)'
return 0;
}