访问模板构造函数和函数,包括静态和非静态
Accessing template constructor and function, both static and non-static
我是模板新手,发现这个东西相当令人困惑。我有一个模板类,它作为一个表,用于将实体映射到字符串,该类的代码如下
template<class GENERIC_ENTITY> class EntityTable
{
private:
map<wstring, GENERIC_ENTITY*> entityTable;
// I want to put init in the default constructor so it gets initialized, but this doesn't compile
EntityTable<GENERIC_ENTITY>::EntityTable () {
init();
}
void init()
{
entityTable[L"Entity1"] = new Entity1();
entityTable[L"Entity2"] = new Entity2();
entityTable[L"Entity3"] = new Entity3();
}
public:
// This function doesn't compile unless I remove the keyword static
static template <class GENERIC_ENTITY> GENERIC_ENTITY retriveEntity(wstring identifier)
{
return entityTable[identifier];
}
};
然后我想在另一个类中调用这个模板函数,并使用wstring
标识符检索相应的实体。但不幸的是,我既不能构造类,也不能调用这个函数,不管这个函数是否是静态的。它甚至不能编译。
如果函数是静态的,我想做一些像EntityTable<T>::retriveEntity(wstring)
,如果不是静态的,我想首先实例化它,但我不知道如何用模板做,因为我听说模板不是一个类。我将它声明为堆栈上的实际数据,所以我不必在构造函数中调用new,我不知道它是什么样子,但我仍然无法访问该函数。
我完全糊涂了,谁能帮我理清头绪?
编辑:顺便说一句,我在另一个类中声明这个模板的方式是template<class GENERIC_BOT> EntityTable entityTable;
。不确定这是否正确
所有的实体类继承自两个共同的类(纠正一个的错误),但这些类是抽象的,所以我不能实例化它只是做一些像Entity retrieveEntity(wstring info)
我希望这个类是一类单例,在初始化的地方构造它,并在任何地方调用静态函数。映射在构建之后是不可变的。wstring
被传递给模板,模板将返回与wstring
标签相关联的相应类。我只需要一种快速的检索方式,考虑到表很大的情况,为了方便,我只显示了两个项目。
注:我知道我也可以使用if或switch语句返回相应的类型,但是那样又长又麻烦,并且违背了使用map
应该可以正常编译:
template<class GENERIC_ENTITY> class EntityTable
{
private:
map<wstring, GENERIC_ENTITY*> entityTable;
EntityTable::EntityTable () {
init();
}
void init()
{
entityTable[L"Entity1"] = new Entity1();
entityTable[L"Entity2"] = new Entity2();
entityTable[L"Entity3"] = new Entity3();
}
public:
GENERIC_ENTITY* retriveEntity(wstring identifier)
{
return entityTable[identifier];
}
};
如果您希望它是静态的,只需应用单例模式或声明entityTable static。在这种情况下,没有构造函数可用,init()也必须是静态的,并在代码中的某个点调用。单例可以保证init()只被调用一次。
- 包括带有 cmake 的静态库
- 是否可以链接到,包括和使用静态库,而无需额外包含标头/文件
- Bazel - 导入静态库时包括目录中的所有标头
- 包括不排除静态库项目的用户路径的路径
- 包括在自制静态库的标头文件中使用的库
- cmake-包括静态库中的依赖项
- 确实被认为是实验性的 - 静态反射功能包括对母类的迭代
- 我应该包括外部库的src代码还是从外部库构建的静态库
- QString:包括非文本类型的静态数据成员的初始化
- 为什么包括-FPIC来编译静态库会在运行时会导致分割故障
- 包括静态库中的STL
- 包括静态数据/文本文件
- 如何强制依赖静态对象(包括模板成员)的初始化顺序
- 静态提升达尔文,包括libstdc++
- SWIG - 包括使用cygwin的现有静态C++库(.lib)
- C++中类的静态变量初始化,为什么包括数据类型
- 静态库头文件包括其他头文件。我是否需要这些头文件的实现/源文件?
- 访问模板构造函数和函数,包括静态和非静态
- 包括错误与pjsip作为静态库在Android NDK项目
- C++Visual Studio-多项目解决方案-“;静态lib”;vs“;包括目录”;