带有函数指针和引用的模板参数推导
Template parameter deduction with function pointers and references
可能重复:
为什么在推导类型时会剥离模板参数的限定符?
考虑以下C++代码:
void f(int&);
template <typename T> void tpl(void (*)(T), T);
void bar(int& x)
{
tpl(&f, x);
}
使用GCC 4.6.0编译失败,并显示以下错误消息:
fntpl.cpp: In function ‘void bar(int&)’:
fntpl.cpp:7:11: error: no matching function for call to ‘tpl(void (*)(int&), int&)’
fntpl.cpp:7:11: note: candidate is:
fntpl.cpp:3:46: note: template<class T> void tpl(void (*)(T), T)
如果我明确地说明模板参数(tpl<int&>(&f, x)
(,它就可以工作了。为什么在这种情况下模板参数推导不起作用?
因为它们是根本不同的
void f(int&);
和
void (*)(T)
编译器只推导出T
是int
,所以它寻找:
void f(int);
这与你的意图完全不同,将函数指针改为:
template <typename T> void tpl(void (*)(T&), T);
编译器会很高兴。。。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 通过常量引用传递参数的矩阵模板类
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 何时应通过引用传递矢量参数而不是按值传递矢量参数?
- 具有常量引用参数的函数模板专用化
- 作为参数引用
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 如何传递带有通过引用传递的结构参数的函数?
- 将输入参数作为右值引用传递?
- 使用引用与指针将数组作为参数传递
- 根据模板参数引用不同基类的函数
- 默认情况下C++数组作为参数引用
- 对指针C++的参数引用
- 作为非类型模板参数引用
- 重用返回语句或按参数引用返回
- 将参数引用传递给函数C++
- 从另一个参数引用的模板可变参数
- 成员变量多态性和参数引用
- 按参数引用或按参数引用之间的差异
- 无法实例化抽象类:为什么模板参数(引用)导致这种情况