gpt4 book ai didi

c++将参数传递给线程作为引用不起作用

转载 作者:行者123 更新时间:2023-12-05 02:35:04 25 4
gpt4 key购买 nike

我写了一段代码来创建线程并将参数作为引用发送给他,但是我在函数名称下看到了一条红色下划线,就像我无法调用它一样。有人知道我的代码出了什么问题

我的代码:

#include "getPrimes.h"

void getPrimes(const int& begin, const int& end, std::vector<int>& primes)
{
int i = 0, j = 0;
for (i = begin; i <= end; i++)
{
if (i > 1)
{
for (j = 2; j <= i / 2; j++)
{
if (i % j != 0)
{
primes.push_back(i);
}
}
}
}
}

std::vector<int> getPrimes(const int& begin, const int& end)
{
std::vector<int> vector;
std::thread thread(getPrimes, std::ref(begin), std::ref(end), std::ref(vector)); // I get the red underline here
}

我得到的错误

enter image description here

最佳答案

由于 getPrimes 被重载,您需要帮助编译器解决重载问题。

例子:

std::vector<int> getPrimes(const int& begin, const int& end) {
std::vector<int> vector;
std::thread thread( // see static_cast below:
static_cast<void(*)(const int&, const int&, std::vector<int>&)>(getPrimes),
std::cref(begin), std::cref(end), std::ref(vector));
// ...
thread.join();
return vector;
}

一个简化的例子:

void foo(int) {}
void foo(int, int) {}

int main() {
// auto fp = foo; // same problem - which foo should fp point at?

// same solution:
auto fp = static_cast<void(*)(int)>(foo);
}

关于c++将参数传递给线程作为引用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70632917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com