12

可能重复:

std::bind 重载决议

考虑以下 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' :不能推断模板参数,因为函数参数不明确。我该如何解决这种歧义?

4

2 回答 2

15

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

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); });
于 2014-11-20T07:14:15.913 回答
4

std::bind 重载解决方案的帮助下,我为我的问题找到了解决方案。有两种方法可以做到这一点(根据我)。

  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)
    
于 2014-11-20T07:17:06.707 回答