问题描述
我一直在尝试使用模板成员函数在我的类中设置一个值。我想使用通用引用,以便我可以接受正确类型的任何变体(例如 T
, T&
, T&&&
, const T
, const T&
, const T&&&
)
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&&
)
然而,似乎我的成员函数只接受rvalues一个自由函数接受一个通用引用。
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;
}
推荐答案
code> Foo 被实例化为 Foo 。一旦发生这种情况,类模板将被实例化如下:
In the code given, Foo
is instantiated as Foo<int>
. Once this happens, the class template is instantiated as shown:
class Foo{
public:
void memberURef(int&& t){ // Uh oh!
val = std::forward<int>(t);
}
private:
int val;
};
请注意成员函数不再是模板,因此不再接受通用引用,右值引用。为了使成员函数接受一个通用引用, Foo
类需要修改如下:
Notice how the member function is no longer a template, and therefore no longer accepts a universal reference, but an rvalue reference. In order to make a member function that accepts a universal reference, the Foo
class would need to be modified as follows:
template <typename T>
class Foo{
public:
template <typename L>
void memberURef(L&& t){
val = std::forward<L>(t);
}
private:
T val;
};
这样, memberURef
em>函数模板,因此它仍然接受一个通用引用。
That way, memberURef
is still a function template after the class template has been instantiated, and it thus still accepts a universal reference.
这篇关于具有通用引用的成员函数模板将不接受lvalue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!