【问题标题】:ERROR: std::thread arguments must be invokable after conversion to rvalues错误:std::thread 参数在转换为右值后必须是可调用的
【发布时间】:2021-04-08 17:38:25
【问题描述】:

我正在尝试构建这个相对简单的代码,但由于标题中提到的错误而失败。我已经看了几次代码,但未能弄清楚是什么愚蠢导致了这种情况。有人可以给个提示或线索吗?

#include <thread>
#include <iostream>
#include <vector>
#include <chrono>
#include <mutex>
#include <functional>


std::vector<std::vector<double>> v2d;

int fill_the_vec(std::vector<double>& inp, int sz){
    for(int i = 0; i < sz; i++)inp.push_back(i * 2.0);
    return 0;
}

int fill_vec_mt(int r, int c){
    for(int i = 0; i < r; i++)v2d.push_back({});
    std::vector<std::thread> tv;

    for(int i = 0; i < r; i++){
        tv.emplace_back((fill_the_vec, std::ref(v2d[i]), c));
    }
    for (auto &t : tv)
        if(t.joinable())
            t.join();
    return 0;
}

int main(){
    
    fill_vec_mt(10, 1000);

    for(int i = 0; i < v2d.size(); i++){
        double t = 0;
        for(int j = 0; j < v2d[i].size(); j++){
            t += v2d[i][j];
        }
        std::cout <<  "Sum at place " << i << "is " << t << std::endl;
    }

    return 0;
}

【问题讨论】:

  • 您的 emplace_back 调用中有额外的括号。你现在拥有它的方式相当于tv.emplace_back(c);
  • 哦。 。非常感谢!您可以将其添加为我接受的答案吗?
  • My compiler gives a warning here。如果可以的话,你应该调整你的警告标志。

标签: c++ pass-by-reference stdthread


【解决方案1】:

你的陈述

tv.emplace_back((fill_the_vec, std::ref(v2d[i]), c));

正在调用comma operator,它评估其左参数,然后返回其右参数。因此,fill_the_vecstd::ref(v2d[i]) 将被评估并丢弃,然后

tv.emplace_back(c)

将被评估,这将不起作用,因为 c 不可调用。

要解决此问题,请删除多余的括号:

tv.emplace_back(fill_the_vec, std::ref(v2d[i]), c);

这将 3 个参数传递给 emplace_back,正如您所期望的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多