纯虚拟方法 VS。 函数指针
最近我在设计一个Thread类库,我做了一个Thread抽象类,如下所示:
class Thread {
public:
run() { /*start the thread*/ }
kill() { /*stop the thread*/ }
protected:
virtual int doOperation(unsigned int, void *) = 0;
};
真正的线程类会继承这个抽象类,并在自己的逻辑中实现doOperation
方法,类似于策略模式。
问题是我依赖于一个 C 后端库,它定义了在以下函数中运行线程:
int startThread(char* name, (int)(*)(unsigned int, void*), int, int, int, void*);
如您所见; 第二个参数是指向线程循环(主函数)的函数指针,这就是问题所在; 由于我使用此 C 函数在 run
方法中启动线程,因此我将 doOperation
的地址传递给第二个参数,但由于类型原因,这是无法完成的不匹配。
我尝试使用reinterpret_cast
返回指针,但ISO-C++禁止返回未初始化函数成员的指针。 我不知道如何克服这个冲突,我猜使用静态方法是唯一的解决方案,但它破坏了我的设计模式!
Recently I've been designing a Thread class library, I've made a Thread abstract class like the following:
class Thread {
public:
run() { /*start the thread*/ }
kill() { /*stop the thread*/ }
protected:
virtual int doOperation(unsigned int, void *) = 0;
};
Real thread classes would inherit this abstract class and implement doOperation
method in its own logic, something similar to Strategy Pattern.
The problem is that I'm relying on a C back-end library which defines running the thread in the following function:
int startThread(char* name, (int)(*)(unsigned int, void*), int, int, int, void*);
As you can see; the second parameter is a function pointer to thread's loop (main function), and here is the problem; since I use this C-function to start the thread in the run
method, I pass the address of doOperation
to the second parameter, and this cannot be done, because of type mismatch.
I've tried to use reinterpret_cast
to return a pointer, but I ISO-C++ forbids returning a pointer of un-initialized function member.
I don't know how to overcome this conflict, using a static method is the only solution I guess, but it blows up my designing pattern!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,请务必阅读 Michael Burr 提供的链接,因为它包含有用的信息。 然后,这里是它的 C++ 伪代码:
这个想法是 doOperation 作为 Thread 的成员函数,不需要 void *context,您可以将作为上下文传递的任何内容保留在对象中本身。 因此,您可以使用 void 指针将实际的 this 指针传递给 doOperation。 请注意,void * 详细信息对您的类的用户是隐藏的,这很好。
First, be sure to read the link Michael Burr provided, as it contains good information. Then, here is C++ish pseudo-code for it:
The idea is that doOperation, being a member function of Thread, doesn't need a void *context, you can just keep whatever you would pass as a context in the object itself. Therefore, you can use the void pointer to pass the actuall this pointer to the doOperation. Notice that the void * details are hidden from the users of your class, which is nice.