samedi 21 février 2015

Member function template with universal reference won't accept lvalues

I've been trying to use a template member function to set a value inside of my class. I wanted to use a universal reference so that I could accept any variant of the correct type (e.g. T, T&, T&&, const T, const T&, const T&&)


However, it seems that my member function will only accept rvalues, unlike a free function accepting a universal reference.



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;
}

Aucun commentaire:

Enregistrer un commentaire