模板超类的静态成员定义



我需要将(几个)类的实例与小整数相关联,我称之为句柄

我不喜欢使用预处理器宏,所以我想我应该使用模板和多重继承。

我定义了一个Handle类,如下所示:

#include <map>
template<typename Key, typename Self>
class Handle
{
protected:
    static Key nextHandle;
    static std::map<Key, Self*> handles;
    Key handle;
public:
    Handle()
    {
        handles[nextHandle++] = this;
    }
    virtual ~Handle()
    {
        handles.erase(handle);
    }
    static Self * byHandle(Key handle)
    {
        typename std::map<Key, Self*>::const_iterator it = handles.find(handle);
        if(it == handles.end())
            return nullptr;
        else
            return it->second;
    }
    Key getHandle()
    {
        return handle;
    }
};

这种"模式"的用法是:

class Test : public SomeSuperclass, ... , public Handle<int, Test>
{
public:
    Test();
};
Test::Test()
    : Handle()
{
}
int Handle<int, Test>::nextHandle = 666;
std::map<int, Test*> Handle<int, Test*>::handles;

问题就在这里^^^我不知道如何定义那些静态变量的存储,我从clang++中得到了这个错误:

handle_test.cpp:17:24:错误:模板专用化需要"template<>'

int句柄::nextHandle=666;

或者,如果我尝试在Test类中定义它,例如:

int Test::nextHandle = 666;
std::map<int, Test*> Test::handles;

我得到了另一个错误:

handle_test.cpp:20:11:error:"test"中没有名为"nextHandle"的成员

int测试::nextHandle=666;

如果您想要模板专业化的静态成员定义,您可以:

template<>
int Handle<int, Test>::nextHandle = 666;
template<>
std::map<int, Test*> Handle<int, Test>::handles;

如果您想要主模板的静态成员定义,您可以:

template<typename Key, typename Self>
Key Handle<Key, Self>::nextHandle;
template<typename Key, typename Self>
std::map<Key, Self*> Handle<Key, Self>::handles;

您不能在派生类Test上定义它们,它们是Handle的成员。

最新更新