C++中是否可以通过非模板函数访问全局模板变量
Is it possible in C++ to access to global template variable through non template function
我有模板类应用程序
它应该是类似于单例的东西,我想创建一次,然后从其他文件中获取。
//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();
应用程序的构造函数必须在父类中注册单一实例。
相关文章:
- 如何使用 c++ 中的函数访问全局变量?
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 访问全局数据结构
- 访问全局或静态对象的分离线程
- 可以静态访问全局静态变量的静态函数
- C++中是否可以通过非模板函数访问全局模板变量
- 如何在可执行文件中从.so访问全局变量
- C++:为什么与访问全局变量相比,访问类数据成员如此缓慢
- C++ 如何从全局对象中的成员对象访问全局对象
- 访问全局静态变量
- C++-访问全局变量对象
- 访问全局变量以修改值
- 如何访问全局类实例
- 使用PThreads访问全局列表-指针问题
- 如何从另一个.cpp文件访问全局结构
- 无法从 Visual C++ 窗体应用程序中的窗体访问全局变量
- 访问全局数组比作为参数传递更有效
- 声明和访问全局对象
- c++从类头文件中访问全局整数
- 类不能访问全局对象