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

2020-05-18 19:18:37 +08:00
 auto8888
成员函数:
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 类成员函数(成员函数的参数还有成员函数,有点绕,汗)不能作为线程函数吗?
还是我写法有问题啊
3465 次点击
所在节点    C++
10 条回复
codehz
2020-05-18 19:45:13 +08:00
0202 年了,为何不直接用 lambda...可读性都好很多
kidtest
2020-05-18 20:13:10 +08:00
应该是写法有问题,可以贴一下更完整的代码,或者去网上搜一搜 "std::thread member function",对比一下。
FH0
2020-05-18 20:13:51 +08:00
@codehz lambda 确实方便,就是套娃 lambda 之后缩进不美观
codehz
2020-05-18 20:14:45 +08:00
@FH0 (clang-format 的受害者+1
chinuno
2020-05-18 20:52:59 +08:00
好久没用函数指针了。你用 std:: function<void(Adas*, std::string)>不好吗
newmlp
2020-05-18 20:57:12 +08:00
mem_fn
wtof
2020-05-19 10:03:23 +08:00
可能其他地方写错了?
我简单试了试 bind 的语法应该是没什么问题的,msvc 、gcc 都可以过
https://godbolt.org/z/Ivuc2b
auto8888
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
2020-05-19 10:12:11 +08:00
@auto8888 那可能是你 Adas::readStatus 这个函数签名的问题
auto8888
2020-05-19 15:26:26 +08:00
@wtof 是的 是函数签名的问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/672995

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX