【发布时间】:2015-08-04 06:36:01
【问题描述】:
我试图理解为什么std::function 无法区分重载函数。
#include <functional>
void add(int,int){}
class A {};
void add (A, A){}
int main(){
std::function <void(int, int)> func = add;
}
在上面显示的代码中,function<void(int, int)> 只能匹配其中一个函数,但它失败了。为什么会这样?我知道我可以通过使用 lambda 或指向实际函数的函数指针然后将函数指针存储在函数中来解决这个问题。但是为什么会失败呢?我想选择哪个功能的上下文不是很清楚吗?请帮助我理解为什么会失败,因为我无法理解为什么在这种情况下模板匹配会失败。
我在 clang 上遇到的编译器错误如下:
test.cpp:10:33: error: no viable conversion from '<overloaded function type>' to
'std::function<void (int, int)>'
std::function <void(int, int)> func = add;
^ ~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1266:31: note:
candidate constructor not viable: no overload of 'add' matching
'std::__1::nullptr_t' for 1st argument
_LIBCPP_INLINE_VISIBILITY function(nullptr_t) : __f_(0) {}
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1267:5: note:
candidate constructor not viable: no overload of 'add' matching 'const
std::__1::function<void (int, int)> &' for 1st argument
function(const function&);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__functional_03:1269:7: note:
candidate template ignored: couldn't infer template argument '_Fp'
function(_Fp,
^
1 error generated.
编辑 - 除了 MSalters 的回答,我在这个论坛上做了一些搜索,找到了失败的确切原因。我从 Nawaz 在这个post 的回复中得到了答案。
我在这里复制了他的回答:
int test(const std::string&) {
return 0;
}
int test(const std::string*) {
return 0;
}
typedef int (*funtype)(const std::string&);
funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!
那么为什么std::function<int(const std::string&)> 不能像上面的funtype fun = test 那样工作?
答案是,因为std::function 可以用任何对象初始化,因为它的构造函数是模板化的,这与您传递给std::function 的模板参数无关。
【问题讨论】:
-
哪个编译器失败了?
-
gcc 4.8、clang 和 Visual Studio 2013。如果需要,我可以发布编译器错误,尽管它们不是很友好。
-
编译器错误通常不友好但值得发布,奇怪的是,这在这里变得模棱两可,几乎就像
A类的类型在某种程度上被视为与int相同,确实如果您将add声明为采用doubles,错误仍然会发生? -
是的。当我在第二个函数中将参数类型更改为 double 时,它失败了。我已经编辑了问题以包含我遇到的错误。
-
类似问题及其答案:stackoverflow.com/a/12500492/678093
标签: c++ c++11 overload-resolution std-function