【问题标题】:std::async with overloaded functions带有重载函数的 std::async
【发布时间】:2014-11-21 05:08:57
【问题描述】:

可能重复:

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

【问题讨论】:

    标签: c++ overloading stdasync


    【解决方案1】:

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

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

    【讨论】:

    • 当我使用 lambda 表达式时,auto f = std::async(std::launch::async, [&amp;a] { a.foo(2, 3.5); }); int x = f.get(); 不起作用。有什么特殊的获取价值的方法吗?
    • @AmithChinthaka return a.foo(2, 3.5);
    【解决方案2】:

    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)
      

    【讨论】:

      猜你喜欢
      • 2014-09-30
      • 2021-03-04
      • 2020-09-10
      • 2016-08-22
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多