简体   繁体   中英

c++ pass parameters to thread as reference not working

I wrote a code that create thread and send to him parameters as reference, but I get an red underline under the function name like I cant call it. Someone know what went wrong in my code

my code:

#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
}

the error I get

在此处输入图像描述

Since getPrimes is overloaded, you'll need to help the compiler with the overload resolution.

Example:

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

A simplified example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM