将指针到成员函数作为指针到函数 [英] Passing pointer-to-member-function as pointer-to-function

查看:194
本文介绍了将指针到成员函数作为指针到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里的情况:我使用C ++,SDL和GLConsole在一起。我有一个类 SDLGame ,它有 Init() Loop / code>, Render()等 - 本质上,它拥有我的游戏类的逻辑。

GLConsole是一个很好的库远 - 它让我定义CVars等,甚至在我的SDL类。但是,在定义命令时,我必须指定一个 ConsoleFunc ,它被typedef定义为

So here's the situation: I'm using C++, SDL and GLConsole in conjunction. I have a class, SDLGame, which has the Init(), Loop(), Render() etc - essentially, it holds the logic for my game class.
GLConsole is a nice library so far - it lets me define CVars and such, even inside my SDL class. However, when defining commands, I have to specify a ConsoleFunc, which is typedef'd as

typedef bool (*ConsoleFunc)( std::vector<std::string> *args);

很简单。但是,像我说的,我的函数都在我的类,我知道我不能传递指针到类函数作为指针到函数的参数。我不能定义静态函数或使我的类外的函数,因为一些这些ConsoleFuncs必须访问类数据成员是有用的。我想保留它OOP,因为 - 好,OOP是好的。

Simple enough. However, like I said, my functions are all in my class, and I know I can't pass pointer-to-class-functions as pointer-to-function arguments. I can't define static functions or make functions outside my class because some of these ConsoleFuncs must access class data members to be useful. I'd like to keep it OOP, since - well, OOP is nice.

好吧,我实际上有这个问题解决 - 但它是非常丑陋。我只有一个 SDLGame 的实例声明为extern变量,并在我的ConsoleFuncs / main类中使用。

Well, I actually have this problem "solved" - but it's extremely ugly. I just have an instance of SDLGame declared as an extern variable, and use that in my ConsoleFuncs/main class.

所以,问题是:有没有办法做这个不是愚蠢和愚蠢像我这样做的方式? (或者:有一个控制台库,如GLConsole支持SDL,可以做我在描述什么?)

So, the question is: Is there a way to do this that isn't stupid and dumb like the way I am doing it? (Alternatively: is there a console library like GLConsole that supports SDL and can do what I'm describing?)

推荐答案

成员函数需要一个这个指针被调用,如果你没有办法传递它,你运气不好(我猜 std :: vector< std :: string> * args 指针是你从库中传递的)。

A member function needs a this pointer to be called, and if you have no way of passing that, you're out of luck (I guess the std::vector<std::string>* args pointer is what you get passed from the library).

换句话说,即使该库使用C ++容器,它不是一个好的C ++库,因为它依赖于自由函数用于回调。一个好的C ++库会使用 boost :: function 或类似的东西,或者至少让你传递一个 void * user_data 指针传递到你的回调。如果你有这个,你可以传递这个指针的类,将它放回回调,并调用适当的成员函数。

In other words, even though that library uses C++ containers, it's not a good C++ library, because it relies on free functions for callbacks. A good C++ library would use boost::function or something similar, or would at the very least let you pass a void* user_data pointer that gets passed through to your callback. If you had that, you could pass the this pointer of your class, cast it back inside the callback, and call the appropriate member function.

这篇关于将指针到成员函数作为指针到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆