[C++] std::thread 使用重载函数

出错代码

#include <thread>
#include <iostream>
#include <utility>
#include <vector>
#include <string>

char readProcTask(const std::string &cmd, struct timespec &sample_time, std::vector<ProcInfo> &procs) {
    ...
}

char readProcTask(int32_t pid, struct timespec &sample_time, std::vector<ProcInfo> &procs) {
    ...
}

int main() {
    // sample for 500 ms
    struct timespec tm{};
    tm.tv_sec = 0;
    tm.tv_nsec = 1 * 500 * 1000 * 1000; /* 500 ms */

    std::vector<ProcInfo> procs;
    printf("Roboeye_server:\n");
    readProcTask("Roboeye_server", tm, procs);
    std::thread aa(readProcTask, "Roboeye_server", tm, procs);
}

报错信息

No matching constructor for initialization of 'std::thread' candidate template ignored:
couldn't infer template argument '_Callable' candidate constructor not viable: 
requires 1 argument, but 4 were provided candidate constructor not viable: 
requires 1 argument, but 4 were provided candidate constructor not viable: 
requires 1 argument, but 4 were provided candidate constructor not viable: 
requires single argument '__t', but 4 arguments were provided candidate constructor not viable: 
requires 0 arguments, but 4 were provided

解决办法

重载函数的函数签名(signature)不同,是不同的函数。当开发者想绑定一个重载函数而仅给出名字时,编译器无法判定希望绑定的是哪一个函数,就会抛出编译错误。
所以当有作为参数传递的重载函数时,需要声明使用哪个重载函数。

正确代码

#include <thread>
#include <iostream>
#include <utility>
#include <vector>
#include <string>

char readProcTask(const std::string &cmd, struct timespec &sample_time, std::vector<ProcInfo> &procs) {
    ...
}

char readProcTask(int32_t pid, struct timespec &sample_time, std::vector<ProcInfo> &procs) {
    ...
}

int main() {
    // sample for 500 ms
    struct timespec tm{};
    tm.tv_sec = 0;
    tm.tv_nsec = 1 * 500 * 1000 * 1000; /* 500 ms */

    std::vector<ProcInfo> procs;
    printf("Roboeye_server:\n");
    readProcTask("Roboeye_server", tm, procs);
    using f1 = char (*)(const std::string &, struct timespec &, std::vector<ProcInfo> &);
    std::thread aa(static_cast<f1>(readProcTask), "Roboeye_server", std::ref(tm), std::ref(procs));
}

原文链接: https://www.cnblogs.com/jiangyibo/p/17039752.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    [C++] std::thread 使用重载函数

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/310938

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午11:47
下一篇 2023年2月16日 上午11:48

相关推荐