【发布时间】:2017-09-06 21:02:57
【问题描述】:
我正在试验模板和转发。写了一些让我吃惊的简单实验代码。我想更好地理解这个机制,可能我在这里缺乏一些知识,因此我请求帮助。您能否解释一下为什么我在下面的代码中的两个调用无法编译(PLACE 2 和 3)?
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
void h2rvalref(int&& i) { cout << "h2rvalref" << endl; }
void h2ref(int& i) { cout << "h2ref" << endl; }
void h2val(int i) { cout << "h2val" << endl; }
template <class T, class X>
void h1(T&& t, X x) { x(forward<T>(t)); }
int main()
{
// PLACE (1)
h1<int, decltype(h2rvalref)>(1, h2rvalref);
auto b = 1;
// PLACE (2)
// h1<int, decltype(h2ref)>(b, h2ref); // --> ERROR - no matching function..., cannot convert 'b' (type 'int') to type 'int&&'
// PLACE (3)
// h1<int, decltype(h2val)>(b, h2val); // --> ERROR - no matching function..., cannot convert 'b' (type 'int') to type 'int&&'
}
我不明白为什么当我有 int 类型的值 b 时,错误说明了将 int 转换为 int&& 的内容。
【问题讨论】:
-
不要注释掉您询问的代码。语法突出显示使其难以阅读。
-
好的,我会记住的。
标签: c++