首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过std::function包装重载函数

通过std::function包装重载函数
EN

Stack Overflow用户
提问于 2012-04-12 01:35:03
回答 1查看 3K关注 0票数 10

我有一个重载的函数,我想将其封装在std::function中传递。GCC4.6没有找到“匹配函数”。虽然我在这里确实发现了一些问题,但答案并不像我希望的那样清晰。谁能告诉我为什么下面的代码不能推导出正确的重载,以及如何(优雅地)解决它?

代码语言:javascript
复制
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();
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-12 01:39:06

这是一种模棱两可的情况。

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

代码语言:javascript
复制
typedef int (*funtype)(const std::string&);

std::function<int(const std::string&)> func=static_cast<funtype>(test);//cast!

现在,编译器将能够根据强制转换中的类型消除这种情况的歧义。

或者,您可以这样做:

代码语言:javascript
复制
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的模板参数。

票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10111042

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档