std::async with overloaded functions
Asked Answered
M

2

12

Possible Duplicate:

std::bind overload resolution

Consider following C++ example

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

This gives 'std::async' : cannot deduce template argument as function argument is ambiguous. How do I resolve this ambiguity??

Must answered 20/11, 2014 at 6:44 Comment(0)
P
17

Help the compiler resolve ambiguity telling which overload you want:

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

or use lambda expression instead:

std::async(std::launch::async, [&a] { return a.foo(2, 3.5); });
Package answered 20/11, 2014 at 7:14 Comment(2)
When I'm using the lambda expressionauto f = std::async(std::launch::async, [&a] { a.foo(2, 3.5); }); int x = f.get(); is not work. Is there any especial way of getting the value?Must
@AmithChinthaka return a.foo(2, 3.5);Package
M
4

With the help of std::bind overload resolution I figure out a solution for my question. There are two way of doing this (according to me).

  1. Using 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. Directly using above function binding

    auto f = std::async(std::launch::async, (int(A::*)(int, double))&A::foo, &a, 2, 3.5)
    
Must answered 20/11, 2014 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.