【问题标题】:What is the correct way of calling a template function using std::async使用 std::async 调用模板函数的正确方法是什么
【发布时间】:2018-04-20 21:28:28
【问题描述】:

我正在尝试了解std::async 的用途。我写了下面的模板函数来累积一个整数数组中的所有条目。

template<typename T, int N, typename = std::enable_if<std::is_integral<T>::value>::type>
T parallel_sum(T(&arr)[N], size_t start = 0, size_t end = N - 1) {
    if (end - start < 1000) {
        return std::accumulate(std::begin(arr) + start, std::begin(arr) + end + 1, 0);
    }
    else {
        size_t mid = start + (end - start) / 2;
        auto res1 = std::async(std::launch::async, parallel_sum<T, N>, arr, start, mid);
        auto res2 = parallel_sum(arr, mid + 1, end);
        return res2 + res1.get();
    }
}

当我在 main 中调用上述函数时,出现以下编译错误(以及更多错误):

错误 C2672:“std::async”:找不到匹配的重载函数

为什么会出现此错误?怎么解决?

【问题讨论】:

    标签: c++ c++11 templates


    【解决方案1】:

    您应该使用std::ref 来保留引用语义。

    变化是线:

    auto res1 = std::async(std::launch::async, parallel_sum<T, N>, arr, start, mid);
    

    到:

    auto res1 = std::async(std::launch::async, parallel_sum<T, N>, std::ref(arr), start, mid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      相关资源
      最近更新 更多