微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

std::thread Args... 列表中的函数指针

如何解决std::thread Args... 列表中的函数指针

我试图给我的 std::thread 参数列表提供一个函数指针,但我收到了一堆我不明白的编译错误 (@ MSVC\14.28.29333\include\thread(43,14): error C2672: 'invoke' : fonction correspondante surchargée introuvable [overloaded function not found])。

我可以写一个 mcve 给出同样的错误

#include <thread>
#include <vector>

template<typename T>
void worker(std::vector<T>& data_set,void(*do_something)(T&)) {
    for (T& t : data_set)
        (*do_something)(t);
}

template<typename T>
std::vector<T> get_data(void(*do_something)(T&),size_t sz) {

    //only 1 thread as example
    std::vector<T> data_set(sz);
    std::thread t1(worker<T>,data_set,do_something); //compile error
    t1.join();


    worker<T>(data_set,do_something); //this on the other hand does compile

    return data_set;
}

void do_something_int(int& i) {
    i = 1;
}

void do_something_float(float& f) {
    f = 2.1f;
}

void do_something_char(char& c) {
    c = 'a';
}

int main(int argc,char** argv) {

    auto data_set_int = get_data(&do_something_int,100);
    auto data_set_float = get_data(&do_something_float,100);
    auto data_set_char = get_data(&do_something_char,100);

    return 0;
}

有趣的是,如果我以非线程方式调用工作程序,一切都很好。我不知道编译器在期待什么。

解决方法

问题是您的函数通过非常量左值引用接受参数。 std::thread 会将右值传递给函数,非常量左值引用不能绑定到右值。

为了传递一个左值,你必须使用一个引用包装器:

std::thread t1(worker<T>,std::ref(data_set),do_something);

在单独的线程中引用自动对象时,请务必确保所引用对象的生命周期。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。