带有函数指针和引用的模板参数推导

Template parameter deduction with function pointers and references

本文关键字:参数 引用 函数 指针      更新时间:2023-10-16

可能重复:
为什么在推导类型时会剥离模板参数的限定符?

考虑以下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)

编译器只推导出Tint,所以它寻找:

void f(int);

这与你的意图完全不同,将函数指针改为:

template <typename T> void tpl(void (*)(T&), T);

编译器会很高兴。。。