使用函数指针和引用进行模板参数推导
考虑以下 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
),它有效。为什么模板参数推导在这种情况下不起作用?
Possible Duplicate:
Why are qualifiers of template arguments stripped when deducing the type?
Consider the following C++ code:
void f(int&);
template <typename T> void tpl(void (*)(T), T);
void bar(int& x)
{
tpl(&f, x);
}
Compilation using GCC 4.6.0 fails with the following error message:
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)
If I state the template parameters explicitely (tpl<int&>(&f, x)
), it works. Why doesn't template argument deduction work in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为它们根本不同
,并且
编译器仅推断出
T
是int
,因此它会查找:这与您的意图完全不同,请将函数指针更改为此:
并且编译器会很高兴...
Because these are fundamentally different
and
the compiler has only deduced that
T
isint
, so it looks for:which is nothing like your intention, change the function pointer to this:
And the compiler will be happy...