【问题标题】:Template parameter deduction with function pointers and references [duplicate]带有函数指针和引用的模板参数推导[重复]
【发布时间】:2011-07-01 10:57:51
【问题描述】:

可能重复:
Why are qualifiers of template arguments stripped when deducing the type?

考虑以下 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&lt;int&amp;&gt;(&amp;f, x)),它会起作用。为什么在这种情况下模板参数推导不起作用?

【问题讨论】:

  • 表达式x 的类型是int,而不是int &amp;(只要在表达式中使用,引用就会衰减为左值)。编译器错误消息似乎充其量是误导性的。

标签: c++ templates reference function-pointers


【解决方案1】:

因为这些是根本不同的

void f(int&);

void (*)(T)

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

void f(int);

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

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

编译器会很高兴...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2015-01-20
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多