我有一个重载的函数,我想将其封装在std::function中传递。GCC4.6没有找到“匹配函数”。虽然我在这里确实发现了一些问题,但答案并不像我希望的那样清晰。谁能告诉我为什么下面的代码不能推导出正确的重载,以及如何(优雅地)解决它?
int test(const std::string&) {
return 0;
}
int test(const std::string*) {
return 0;
}
int main() {
std::function<int(const std::string&)> func = test;
return func();
}发布于 2012-04-12 01:39:06
这是一种模棱两可的情况。
要消除歧义,请使用显式强制转换为:
typedef int (*funtype)(const std::string&);
std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!现在,编译器将能够根据强制转换中的类型消除这种情况的歧义。
或者,您可以这样做:
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的模板参数。
https://stackoverflow.com/questions/10111042
复制相似问题