访问模板构造函数和函数,包括静态和非静态

Accessing template constructor and function, both static and non-static

本文关键字:静态 包括 函数 构造函数 访问      更新时间:2023-10-16

我是模板新手,发现这个东西相当令人困惑。我有一个模板类,它作为一个表,用于将实体映射到字符串,该类的代码如下

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()只被调用一次。