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

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

  •  
  •   auto8888 · 2020 年 5 月 18 日 · 4181 次点击
    这是一个创建于 2070 天前的主题,其中的信息可能已经有所发展或是发生改变。
    成员函数:
    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 年 5 月 18 日 via Android
    0202 年了,为何不直接用 lambda...可读性都好很多
    kidtest
        2
    kidtest  
       2020 年 5 月 18 日
    应该是写法有问题,可以贴一下更完整的代码,或者去网上搜一搜 "std::thread member function",对比一下。
    FH0
        3
    FH0  
       2020 年 5 月 18 日
    @codehz lambda 确实方便,就是套娃 lambda 之后缩进不美观
    codehz
        4
    codehz  
       2020 年 5 月 18 日
    @FH0 (clang-format 的受害者+1
    chinuno
        5
    chinuno  
       2020 年 5 月 18 日 via Android   ❤️ 1
    好久没用函数指针了。你用 std:: function<void(Adas*, std::string)>不好吗
    newmlp
        6
    newmlp  
       2020 年 5 月 18 日
    mem_fn
    wtof
        7
    wtof  
       2020 年 5 月 19 日
    可能其他地方写错了?
    我简单试了试 bind 的语法应该是没什么问题的,msvc 、gcc 都可以过
    https://godbolt.org/z/Ivuc2b
    auto8888
        8
    auto8888  
    OP
       2020 年 5 月 19 日
    搞定了,
    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 年 5 月 19 日
    @auto8888 那可能是你 Adas::readStatus 这个函数签名的问题
    auto8888
        10
    auto8888  
    OP
       2020 年 5 月 19 日
    @wtof 是的 是函数签名的问题
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   912 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:02 · PVG 04:02 · LAX 12:02 · JFK 15:02
    ♥ Do have faith in what you're doing.