V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
auto8888
V2EX  ›  C++

c++11 std::thread 和 std::bind 请教,成员函数的参数是另一个成员函数

  •  
  •   auto8888 · 2020-05-18 19:18:37 +08:00 · 3431 次点击
    这是一个创建于 1411 天前的主题,其中的信息可能已经有所发展或是发生改变。
    成员函数:
    void Adas::udpBind(unsigned short LocalPort,void (Adas::*fun)(std::string))
    在构造函数里:
    std::bind(&Adas::udpBind,this,this->LocalPort,&Adas::readStatus) 这编译 OK 。
    但是
    std::thread thread1(std::bind(&Adas::udpBind,this,this->LocalPort,&Adas::readStatus));
    thread1.join();
    编译失败了。
    std::thread 类成员函数(成员函数的参数还有成员函数,有点绕,汗)不能作为线程函数吗?
    还是我写法有问题啊
    10 条回复    2020-05-19 15:26:26 +08:00
    codehz
        1
    codehz  
       2020-05-18 19:45:13 +08:00 via Android
    0202 年了,为何不直接用 lambda...可读性都好很多
    kidtest
        2
    kidtest  
       2020-05-18 20:13:10 +08:00
    应该是写法有问题,可以贴一下更完整的代码,或者去网上搜一搜 "std::thread member function",对比一下。
    FH0
        3
    FH0  
       2020-05-18 20:13:51 +08:00
    @codehz lambda 确实方便,就是套娃 lambda 之后缩进不美观
    codehz
        4
    codehz  
       2020-05-18 20:14:45 +08:00
    @FH0 (clang-format 的受害者+1
    chinuno
        5
    chinuno  
       2020-05-18 20:52:59 +08:00 via Android   ❤️ 1
    好久没用函数指针了。你用 std:: function<void(Adas*, std::string)>不好吗
    newmlp
        6
    newmlp  
       2020-05-18 20:57:12 +08:00
    mem_fn
    wtof
        7
    wtof  
       2020-05-19 10:03:23 +08:00
    可能其他地方写错了?
    我简单试了试 bind 的语法应该是没什么问题的,msvc 、gcc 都可以过
    https://godbolt.org/z/Ivuc2b
    auto8888
        8
    auto8888  
    OP
       2020-05-19 10:09:02 +08:00
    搞定了,
    void Adas::udpBind(unsigned short LocalPort,void (Adas::*fun)(std::string))改为
    void Adas::udpBind(unsigned short LocalPort,void (Adas::*fun)(const std::string&))
    就行了,别问我 我也不知道为什么。。。。。
    还有 lambda
    std::thread thread1([=] {udpBind( mStatus_Port,&Adas::readStatus); });
    thread1.join();
    有一说一,lambda 有点帅气。。
    wtof
        9
    wtof  
       2020-05-19 10:12:11 +08:00
    @auto8888 那可能是你 Adas::readStatus 这个函数签名的问题
    auto8888
        10
    auto8888  
    OP
       2020-05-19 15:26:26 +08:00
    @wtof 是的 是函数签名的问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2823 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:14 · PVG 21:14 · LAX 06:14 · JFK 09:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.