c++ - 右值引用匹配(完美转发示例)

标签 c++ c++11 rvalue-reference

我被下面的完美转发函数搞糊涂了,模板参数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>
}

我不明白为什么模板参数推导为Tfoo在这两种情况下如此不同?什么是根本区别,重要的是什么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&
}

另外,引用折叠规则是一本好书。

检查这个以获得一个非常好的解释:

perfect forwarding

关于c++ - 右值引用匹配(完美转发示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32935343/

相关文章:

c++ - 更改包含的 makefile 中的文件路径

c++ - 如何将浮点算法转换为定点算法?

c++ - 如何查看VS2010生成的汇编语言?

c++ - 为什么互斥引用上的 lock_guard 会产生 C26110

c++ - 在 C++ 中调用 delete/delete[] 时中断调试器

c++ - 常数整数提升规则?

c++ - 为什么我不能在函数中使用 constexpr 值,但我可以在这个值的范围内做同样的事情?

c++ - 普通的右值引用和 std::forward 返回的有什么区别?

c++ - 不同的构造函数调用取决于编译器

C++ 简化构造函数重载