如何为单例函数创建别名?

发布于 2024-09-17 18:10:41 字数 143 浏览 3 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

画骨成沙 2024-09-24 18:10:41

使用静态函数。

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

编辑:对不起,小伙子们,我写了 static someFunction ,意思是 void someFunction。

Use a static function.

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

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

温柔一刀 2024-09-24 18:10:41

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.

指尖上得阳光 2024-09-24 18:10:41

查找函数指针。

您可以创建一个函数指针,并将其分配给您的长函数。然后,无论变量在何处定义,您都可以像常规函数一样调用该函数指针。

函数指针可能会令人困惑,但在 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.

月亮邮递员 2024-09-24 18:10:41

你可以这样做
#define someFunctionAlias MYCLASS::GetInstance()->someFunction()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文