C++和成员函数指针

发布于 2024-10-22 06:16:46 字数 154 浏览 2 评论 0原文


我正在尝试将成员函数的地址发送到我的“Thread”类,以便我可以从那里激活它。
我读到我可以使用函子,但我希望它是通用的,我可以将其发送到我的“线程”构造函数,并且函子需要模板,所以这对我来说还不够......

有人知道一种方法吗这样做?
谢谢 :)

I'm trying to send an address of a member function to my "Thread" class so I can activate it from there.
I read that I can use functors but I want it to be generic in a way that I can send it to my "Thread" constructor and functors need templates, so it won't be enough for me...

Does anybody know a way to do this?
thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画中仙 2024-10-29 06:16:46

如果我可以建议一种不同的方法:从线程类派生并创建一个虚拟 Run() 函数。

原因是,虽然可以从静态线程入口函数调用函数指针,但您会面临一个又一个问题。例如,您可以使用模板和可变参数来解决拥有正确函数签名的问题,但这没有多大用处,因为入口函数不知道要发送给您的函数什么

另一方面,从 Thread 派生是简单直接的。您可以将线程需要知道的任何内容放入构造函数中。或者,您可以选择在创建线程之前调用任意数量的其他函数并设置任意数量的成员。创建线程后,静态线程入口函数将简单地调用虚拟 Run 函数。现在... Run 函数是线程对象的一部分,因此它知道类所知道的任何内容——没问题。

与它的简单性相比,单个虚拟函数调用和 vtable 中的一个指针的额外开销也小得离谱。

If I may suggest a different approach: derive from your thread class and make a virtual Run() function.

The reason is that although it is possible to call a function pointer from the static thread entry function, you face problem after problem. For example, you can solve the problem of having the right function signature with templates and variadic parameters, but it is not of much avail, because the entry function won't know what to send to your function.

On the other hand, deriving from Thread is easy and straightforward. You put into the contructor whatever the thread needs to know. Or, optionally, you can call any number of other functions and set any number of members before you create the thread. Once you do create the thread, the static thread entry function will simply call the virtual Run function. Now... the Run function is part of the thread object, so it knows anything the class knows -- no problem.

The extra overhead of a single virtual function call and of one pointer in the vtable is also ridiculously small compared to how easy it is.

蓝眸 2024-10-29 06:16:46

我建议您查看 C++ FAQ Lite 中对此主题的处理。简而言之,指向成员函数的指针是有问题的,但有几种解决方法,以及出于某些目的应避免使用它们的多种原因。

I suggest you look at the treatment of this topic in the C++ FAQ Lite. In short, pointers to member functions are problematic, but there are several work-arounds, as well as a number of reasons why they should be avoided for certain purposes.

一身骄傲 2024-10-29 06:16:46

最后我决定使用此线程中建议的存根函数:
创建线程不接受成员函数
谢谢大家:)

Finally I decided to use a stub function as suggested in this thread:
Create thread is not accepting the member function
thanks everbody :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文