Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过std::function包装重载函数_C++_C++11_Overloading - Fatal编程技术网

C++ 通过std::function包装重载函数

C++ 通过std::function包装重载函数,c++,c++11,overloading,C++,C++11,Overloading,我有一个重载函数,我想把它包装在std::函数中传递。GCC4.6未找到“匹配函数”。 虽然我确实在这里发现了一些问题,但答案并不像我希望的那样清楚。有人能告诉我为什么下面的代码不能扣除正确的重载,以及如何(优雅地)解决它吗 int test(const std::string&) { return 0; } int test(const std::string*) { return 0; } int main() { std::function<int

我有一个重载函数,我想把它包装在std::函数中传递。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();
}
int测试(const std::string&){
返回0;
}
int测试(常量标准::字符串*){
返回0;
}
int main(){
std::function func=测试;
返回func();
}

这是一种模棱两可的情况

要消除歧义,请使用显式强制转换为:

typedef int (*funtype)(const std::string&);

std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!
typedef int(*funtype)(常量std::string&);
std::function func=static_cast(测试)//铸造
现在,编译器将能够根据强制转换中的类型消除这种情况的歧义

或者,您可以这样做:

typedef int (*funtype)(const std::string&);

funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!
typedef int(*funtype)(常量std::string&);
funtype fun=测试//现在不需要演员!
std::function func=fun//没有演员!
那么为什么
std::function
不能像上面的
funtype-fun=test
那样工作呢


答案是,因为
std::function
可以用任何对象初始化,因为它的构造函数是模板化的,与传递给
std::function
的模板参数无关。请使用
static\u cast
代替旧式cast。@Anonymous:是的。但我想把它缩短。不管怎样,我编辑它使它看起来像C++-ish!多么具有讽刺意味——您必须使用函数指针来获取std::function,而引入std::function是为了避开函数指针:)thx@LCIDFire:
std::function
的引入并不是为了摆脱函数指针,而是为了提供更通用的解决方案。您可以使用
std::function
并使用任何函数指针、lambda、functor(包括binder)。。。