将参数从模板转发到不同类型的函数

Forwarding of parameters from templates to functions of different types

本文关键字:同类型 函数 转发 参数      更新时间:2023-10-16

我正在尝试模板并转发。写了一些简单的实验代码,使我感到惊讶。我想更好地理解这种机制,也许我在这里缺乏知识,因此我寻求帮助。您能解释一下为什么我在下面的代码中的两个电话不编译(第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转换为int&amp; amp;当我有type int.int。

的值时

问题是您向函数提供明确的模板参数。当您明确提供要转发类型的模板参数时,转发参数不起作用(除非您真的知道自己在做什么)。

template <class T, class X>
void h1(T&& t, X x) { x(forward<T>(t)); }

编写h1<int, decltype(h2ref)>时,您会得到这样的函数:

void h1(int&& t, decltype(h2ref) x) { x(forward<int>(t)); }

int&&int不同,不能绑定到类型int的LVALUE,例如您传递的b;它只能绑定到类型int

的rvalues

如果您删除了模板参数,则它只是有效的:

h1(b, h2ref);

这将实例化一个看起来像这样的函数:

void h1(int& t, // int& && collapses to just int&
        decltype(h2ref) x) {
    x(forward<int&>(t));
}