将参数从模板转发到不同类型的函数
Forwarding of parameters from templates to functions of different types
我正在尝试模板并转发。写了一些简单的实验代码,使我感到惊讶。我想更好地理解这种机制,也许我在这里缺乏知识,因此我寻求帮助。您能解释一下为什么我在下面的代码中的两个电话不编译(第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
如果您删除了模板参数,则它只是有效的:
h1(b, h2ref);
这将实例化一个看起来像这样的函数:
void h1(int& t, // int& && collapses to just int&
decltype(h2ref) x) {
x(forward<int&>(t));
}
相关文章:
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- C++ 这里有一个返回 (24) 的布尔返回类型函数
- 使用SFINAE来检测void返回类型函数的存在
- 如何获取同一类函数中类成员的函数指针?
- 使用此类型函数有什么优势
- 为什么此函数通过类型函数指针调用后,呼叫明智地行为
- 如何使用无类型函数指针调用C++成员函数
- 模板返回类型函数如何在C++中工作
- 具有通用类型函数的动态库[C ]
- 如何在返回类型函数模板的专用化中使用派生类型?( "couldn't infer template argument" )
- Bon appetit :从 int 返回类型函数在 main() 中打印字符串
- 对于需要其他模板参数的类型函数的部分模板专业化
- c++错误的参数类型-函数指针
- 延迟评估模板类型函数
- 在引用或指针返回类型函数上输入
- 具有指针数据类型的非类型函数模板参数
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- C++模板基类的非类型函数模板的 using 声明
- 字符串到类型函数,模板专用化使调用统一