具有重载函数的std :: async

时间:2014-11-20 06:44:36

标签: c++ overloading stdasync

  

可能重复:

     

std::bind overload resolution

考虑遵循C ++示例

class A
{
public:
    int foo(int a, int b);
    int foo(int a, double b);
};

int main()
{
    A a;
    auto f = std::async(std::launch::async, &A::foo, &a, 2, 3.5);
}

这给出'std :: async':不能推断模板参数,因为函数参数是不明确的。我该如何解决这种歧义?

2 个答案:

答案 0 :(得分:11)

帮助编译器解决歧义,告诉您需要哪个重载:

std::async(std::launch::async, static_cast<int(A::*)(int,double)>(&A::foo), &a, 2, 3.5);
//                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

或改为使用lambda表达式:

std::async(std::launch::async, [&a] { return a.foo(2, 3.5); });

答案 1 :(得分:3)

std::bind overload resolution的帮助下,我找到了解决问题的方法。有两种方法可以做到这一点(据我所知)。

  1. 使用std::bind

    std::function<int(int,double)> func = std::bind((int(A::*)(int,double))&A::foo,&a,std::placeholders::_1,std::placeholders::_2);
    auto f = std::async(std::launch::async, func, 2, 3.5);
    
  2. 直接使用上述功能绑定

    auto f = std::async(std::launch::async, (int(A::*)(int, double))&A::foo, &a, 2, 3.5)
    
相关问题