我被下面的完美转发函数搞糊涂了,模板参数T
可以匹配右值或左值引用:
template<typename T>
void foo(T&& t){
T::A; // intended error to inspect type
}
int main(){
std::vector<int> a;
std::vector<int> && b = std::move(a);
foo(b); // T is std::vector<int> &
foo(std::move(a)); // T is std::vector<int>
}
我不明白为什么模板参数推导为T
在 foo
在这两种情况下如此不同?什么是根本区别,重要的是什么t
函数中的类型 foo
.
std::move(a)
返回右值引用和 b
已经是右值引用(但有名称)。
是吗,b
s 类型是对 std::vector<int>
的右值引用, 但据我所知,它有一个名称,因此被认为是函数 main 中的左值?
谁能对此有所启发:-)
最佳答案
当 && 与模板一起使用时,有一个特殊的类型推导规则。
template <class T>
void func(T&& t) {
}
"When && appears in a type-deducing context, T&& acquires a special meaning. When func is instantiated, T depends on whether the argument passed to func is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U:"
func(4); // 4 is an rvalue: T deduced to int
double d = 3.14;
func(d); // d is an lvalue; T deduced to double&
float f() {...}
func(f()); // f() is an rvalue; T deduced to float
int bar(int i) {
func(i); // i is an lvalue; T deduced to int&
}
另外,引用折叠规则是一本好书。
检查这个以获得一个非常好的解释:
关于c++ - 右值引用匹配(完美转发示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935343/