这是实现自定义事件处理程序的正确方法吗?
我正在寻找一种将自定义事件处理程序添加为 C++ 类成员函数的方法。发现这段代码确实有效。 我需要将库类和用户代码分开,允许用户代码自定义库类。 这是代码的概念。这样做正确吗?线程安全超出了我的问题范围。编译器是gcc。 用户代码非常非常整洁。没有继承、虚函数、使用的模板
#include <stdio.h>
typedef void fn();
class aaa
{
public:
aaa() : customhandler(NULL) {}
fn *customhandler;
};
// 用户代码开始
void dostuff() {
printf("doing stuff 1\n");
}
void dostuff2() {
printf("doing stuff 2\n");
}
int main()
{
aaa aaa1;
aaa1.customhandler = &dostuff;
aaa1.customhandler();
aaa1.customhandler = &dostuff2;
aaa1.customhandler();
}
I was looking for a way of adding custom event handlers as a c++ class member function. Found that this code actually works.
I need to separate library class and user code, allowing user code to customize library class.
Here is concept of code. Is it correct to do so? Thread safeness is out of scope in my question. Compiler is gcc.
User code is very very neat. no inheritance, virtual functions, templates used
#include <stdio.h>
typedef void fn();
class aaa
{
public:
aaa() : customhandler(NULL) {}
fn *customhandler;
};
// user code start
void dostuff() {
printf("doing stuff 1\n");
}
void dostuff2() {
printf("doing stuff 2\n");
}
int main()
{
aaa aaa1;
aaa1.customhandler = &dostuff;
aaa1.customhandler();
aaa1.customhandler = &dostuff2;
aaa1.customhandler();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,如果您有 Boost 库或支持 C++0x 的编译器,您可能会有这样的代码:
它的好处是您可以将函数或函子绑定到带有可选附加参数的处理程序。
您的原始代码也可以工作,但是如果我想调用类的方法而不是普通函数怎么办?如果我还想传递一些在调用处理程序时可以在处理程序内部访问的状态,该怎么办?这是
std::function
纳入 C++ 标准的众多原因之一。Well, if you had a Boost libraries or C++0x-enabled compiler, you could have had a code like this:
The nice thing about it is that you can have functions or functors bound to a handler with optional additional arguments.
Your original code will also work, but what if I want to invoke a class's method and not a plain function? What if I want to also pass some state that I can access inside the handler when it is invoked? That's one of the many reasons why
std::function
made it into the C++ standard.我尝试了你的代码,效果很好。
仅供参考,还有另一种方法来编码函数指针。在这种情况下,您的代码可以稍微简化一点。这里我对函数指针的typdef使用了稍微不同的语法,它可以让你删除&。符号。
两种方法都很好,我只是想向您展示另一种方法。
I tried your code and it works fine.
Just for your information, there is another way to code your function pointer. In which case your code can be simplified just a little. Here I use a slightly different syntax for the typdef for the function pointer, which lets you drop the & symbols.
Both ways are just fine, I just thought I'd show you another way to do this.