C++中是否可以通过非模板函数访问全局模板变量

Is it possible in C++ to access to global template variable through non template function

本文关键字:访问 全局 变量 函数 可以通过 C++ 是否      更新时间:2023-10-16

我有模板类应用程序

它应该是类似于单例的东西,我想创建一次,然后从其他文件中获取。

//main.cpp
Application<NetworkService, User, Policy> a;
a.run();
//other files
//instead of auto a = Application::getInstance<NetworkService, User, Policy>() I want just
auto a = Application::getInstance()

可能吗?也许以另一种形式,我只是不想使用模板规范来访问创建的早期全局应用程序对象

添加一个类 ApplicationBase,并让应用程序从中继承。 将单一实例访问器放在基类中,并为要调用的所有内容添加虚拟函数。

这样,您将始终与基类进行交互,但您可以使用模板参数在main.cpp中构造它。

class ApplicationBase {
public:
    static ApplicationBase* getInstance() {
        return m_instance;
    }
    virtual void foo() = 0;
protected:
    static ApplicationBase* m_instance;
}
template<TNetworkService, TUser, TPolicy>
class Application : public ApplicationBase {
public:
    Application () {
        m_instance = this;
    }
    virtual void foo() {
        // do something
    }
}

然后在主楼外你可以打电话

auto a = ApplicationBase::getInstance();
a->foo();

应用程序的构造函数必须在父类中注册单一实例。