通过std ::函数包装重载的函数 [英] Wrap overloaded function via std::function

查看:88
本文介绍了通过std ::函数包装重载的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重载函数,我想传递一个包装在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();
}


解决方案

/ p>

要消除歧义,请使用显式强制类型:

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

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

现在编译器能够根据转换的类型来消除这种情况。 p>

或者,您可以这样做:

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

funtype fun = test; //现在不需要施放!
std :: function< int(const std :: string&)> func = fun; //没有施法!

所以为什么 std :: function< int(const std :: string& )> 不工作的方式 funtype fun = test 以上工作?



很好的答案是,因为 std :: function 可以用任何对象初始化,因为它的构造函数是模板化的它独立于传递给 std :: function 的模板参数。


I have an overloaded function which I want to pass along wrapped in a std::function. GCC4.6 does not find a "matching function". While I did find some questions here the answers are not as clear as I would like them. Could someone tell me why the following code can not deduct the correct overload and how to (elegantly) work around it?

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();
}

解决方案

That is ambiguous situation.

To disambiguate it, use explicit cast as:

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

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

Now the compiler would be able to disambiguate the situation, based on the type in the cast.

Or, you can do this:

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

funtype fun = test; //no cast required now!
std::function<int(const std::string&)> func = fun; //no cast!

So why std::function<int(const std::string&)> does not work the way funtype fun = test works above?

Well the answer is, because std::function can be initialized with any object, as its constructor is templatized which is independent of the template argument you passed to std::function.

这篇关于通过std ::函数包装重载的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆