【发布时间】:2020-12-05 11:41:45
【问题描述】:
在std::make_pairthere is only one implementation C++14 onwards
模板 constexpr std::pair
make_pair( T1&& t, T2&& u );
这两个参数都是 R 值引用并根据this
右值引用不能用左值初始化。
int i = 1;
char ch = 'a';
std::unordered_map<int, char> mp;
mp.insert(make_pair<int,char>(i, ch));
因此,当我尝试在上面的代码中使用 make_pair 时,它会正确抛出错误 error: cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'。
但是,如果我更改删除模板参数并将其调用为
,它对于上述代码非常有效mp.insert(make_pair(i, ch));
我很困惑这是如何工作的,因为 i 和 ch 都是 L 值。模板参数解析是否将 L 值转换为 R 值或类似它是如何工作的?
【问题讨论】:
-
这些不是右值引用——它们是forwarding references。他们接受右值和左值。但是,只有当您不明确指定模板参数,但允许模板参数推导完成其工作时,它们才会以这种方式工作。
标签: c++ c++11 templates template-argument-deduction forwarding-reference