我正在阅读 Scott Meyers - Effective Modern C++,尽管我了解何时我可以和不能将左值引用绑定(bind)到通用引用,但我无法理解>原因这背后。
#include <iostream>
#include <string>
class A{
public:
A(std::string && s){}
};
class B{
public:
template<typename T>
B(T&& t){}
};
int main()
{
std::string t;
//A a(t); //won't compile
B b(t); //compiles
return 0;
}
我在传递 t
时没有看到任何未定义的行为,它是对 A()
的左值引用,因此它被绑定(bind)为 std::string &
。为什么仅仅通过类型推导就可以实现?
最佳答案
因为它不是转发(通用)引用。它是一个右值 引用,右值引用不能绑定(bind)到左值。
关于c++ - 为什么只有当它有模板推导时我才能将左值绑定(bind)到通用引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57670613/