我想創建一個C++/QT類模板的工廠,可以用鑰匙用類模板
創建不同的對象的靜態方法奇怪的問題,所以我創建了一個類名爲CFactory,將創建CComponent這是派生從CBaseComponent
Factory.h
#ifndef FACTORY_H
#define FACTORY_H
#include "Header.h"
template <class Object, class Key = QString> class Factory
{
static QMap<Key, Object*> m_map;
public:
static void Register(Key key, Object* obj);
Object* Create(const Key& key);
};
#endif // FACTORY_H
Factory.cpp
#include "factory.h"
template <class Object, class Key> QMap<Key, Object*> Factory<Object, Key>::m_map = QMap<Key, Object*>();
template <class Object, class Key> void Factory<Object, Key>::Register(Key key, Object* obj)
{
if (m_map.find(key) == m_map.end())
{
m_map[key] = obj;
}
}
template <class Object, class Key> Object* Factory<Object, Key>::Create(const Key& key)
{
Object* tmp = 0;
typename QMap<Key, Object*>::iterator it = m_map.find(key);
if (it != m_map.end())
{
tmp = ((*it).second)->Clone();
}
return tmp;
}
個
BaseComponent.h
#ifndef BASECOMPONENT_H
#define BASECOMPONENT_H
#include "Header.h"
class CBaseComponent
{
public:
CBaseComponent(){};
~CBaseComponent(){};
};
#endif
Component.h
#ifndef COMPONENT_H
#define COMPONENT_H
#include "BaseComponent.h"
class CComponent :
public CBaseComponent
{
public:
CComponent(){};
~CComponent(){};
};
#endif
Main.cpp的
#include "templatefactorydemo.h"
#include <QtWidgets/QApplication>
#include "Factory.h"
#include "Component.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Factory<CBaseComponent> fac;
Factory<CBaseComponent>::Register(QString("CComponent"), new CComponent);
CBaseComponent *c=fac.Create("CComponent");
return a.exec();
}
當我建立這個錯誤我得到(譯自法文):
錯誤LNK2019無法解析的外部符號「publi c:static void __cdecl Factory :: Register(class QString,class CBaseComponent *)「 (?Register @?$ Factory @ VCBaseComponent @@ VQString @@@@ SAXVQString @@ PAVCBaseComponent @@@ Z) 在函數中引用 _main TemplateFactoryDemo d:\ TRV \ TemplateFactoryDemo \ main.obj 1
你能把它翻譯成英文嗎?我不確定編譯器在說什麼。我猜這是一個鏈接錯誤,但我不確定。 – Cornstalks
http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – lsbbo