如何为单例函数创建别名?
我想在 C++ 中为单例调用创建一个别名 因此,我可以在代码中只调用 someFunctionAlias();
,而不是每次都调用 MYCLASS::GetInstance()->someFunction();
。
I would like to make an alias in C++ to singleton calling
so instead of calling MYCLASS::GetInstance()->someFunction();
each time, I could call just someFunctionAlias();
in my code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用静态函数。
编辑:对不起,小伙子们,我写了 static someFunction ,意思是 void someFunction。
Use a static function.
Edit: Sorry lads, I wrote static someFunction and meant void someFunction.
typedef 用于类型别名,但不能用作调用别名。
函数(例如 DeadMG 建议的函数)可以用作调用“别名”。
附言。因为这是 C++,所以你有很多选项、函数指针、std::tr1::function<> 等。运算符重载和预处理器。但在这种情况下,看起来一个简单的函数肯定是最简单、最好的解决方案。
typedefs are used for type aliases but can't be used as call alias.
functions (such as suggested as by DeadMG) can be used as a call "alias".
PS. As this is C++ you have lots of options, function pointers, std::tr1::function<> operator overloading and the preprocessor. But in this case it certainly looks like a simple function would be the simplest and best solution.
查找函数指针。
您可以创建一个函数指针,并将其分配给您的长函数。然后,无论变量在何处定义,您都可以像常规函数一样调用该函数指针。
函数指针可能会令人困惑,但在 API 回调中被大量使用(即,您将函数作为参数传递给 API,API 将在发生某些情况时调用该函数(想想 WndProc))。
祝你好运。
Look up function pointers.
You can create a function pointer, and assign it to your long function. You can then call this function pointer just like a regular function, wherever your variable is defined.
Function pointers can be confusing, but are used a lot in API callbacks (i.e. you pass a function as an argument to the API, and the API will call that function when something happens (think WndProc)).
Good luck.
你可以这样做
#define someFunctionAlias MYCLASS::GetInstance()->someFunction()
you can do this
#define someFunctionAlias MYCLASS::GetInstance()->someFunction()