abe*_*ier 8 c++ overloading c++11
我有一个重载函数,我想传递包裹在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();
}
Run Code Online (Sandbox Code Playgroud)
Naw*_*waz 18
那种模棱两可的情况.
要消除歧义,请使用显式强制转换为:
typedef int (*funtype)(const std::string&);
std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!
Run Code Online (Sandbox Code Playgroud)
现在,编译器可以根据转换中的类型消除歧义.
或者,你可以这样做:
typedef int (*funtype)(const std::string&);
funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!
Run Code Online (Sandbox Code Playgroud)
那么为什么std::function<int(const std::string&)>不能按funtype fun = test上述方式工作呢?
答案是,因为std::function可以使用任何对象初始化,因为它的构造函数是模板化的,它与您传递给的模板参数无关std::function.