How can I make an alias to a singleton function?

我只是一个虾纸丫 提交于 2019-12-01 09:57:12

问题


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.


回答1:


Use a static function.

namespace ... {
    void someFunction() {
        MYCLASS::GetInstance()->someFunction();
    }
};

Edit: Sorry lads, I wrote static someFunction and meant void someFunction.




回答2:


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.




回答3:


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.




回答4:


you can do this #define someFunctionAlias MYCLASS::GetInstance()->someFunction()



来源:https://stackoverflow.com/questions/3645896/how-can-i-make-an-alias-to-a-singleton-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!