我目前正在從C#轉換到C++,並且我經常碰到路障。我有一個事件處理系統,從一個教程,並嘗試以使其適應我的需要,但也有是我無法理解的錯誤:事件處理程序模板:無法解析的外部
事件:
#pragma once
class Event
{
protected:
virtual ~Event() {};
};
事件處理:
#pragma once
#include "Event.h"
#include "TypeInfo.h"
#include "HandlerFunctionBase.h"
#include <map>
#include <typeindex>
class EventHandler
{
public:
void HandleEvent(const Event*);
template < class T, class EventT >
void RegisterEventFunc(T*, void (T::*memFn)(EventT*));
private:
typedef std::map<std::type_index, HandlerFunctionBase* > Handlers;
Handlers _handlers;
};
[...]
#include "EventHandler.h"
template < class T, class EventT >
void EventHandler::RegisterEventFunc(T* obj, void (T::*memFn)(EventT*))
{
_handlers[std::type_index(typeid(EventT))]=
new MemberFunctionHandler< T, EventT >(obj, memFn);
}
void EventHandler::HandleEvent(const Event* event)
{
Handlers::iterator it = _handlers.find(std::type_index(typeid(*event)));
if(it != _handlers.end())
{
it->second->exec(event);
}
}
HandlerFunctionBase:
#pragma once
#include "Event.h"
class HandlerFunctionBase
{
public:
virtual ~HandlerFunctionBase() {};
void exec(const Event* event) {call(event);}
private:
virtual void call(const Event*) = 0;
};
MemberFunctionHandler:
#pragma once
#include "handlerfunctionbase.h"
template < class T, class EventT >
class MemberFunctionHandler : public HandlerFunctionBase
{
public:
typedef void (T::*MemberFunc)(EventT*);
MemberFunctionHandler(T* instance, MemberFunc memFn) : _instance(instance), _function(memFn) {};
void call(const Event* event)
{
(_instance->*_function)(static_cast< EventT* >(event));
}
private:
T* _instance;
MemberFunc _function;
};
LogHandler
(我自己的類,首先嚐試使用系統)
#pragma once
#include "EventHandler.h"
#include "LogEvent.h"
class LogHandler
{
public:
LogHandler(EventHandler*);
~LogHandler(void);
private:
void Handle(LogEvent*);
};
#[...]
#include "LogHandler.h"
LogHandler::LogHandler(EventHandler *handler)
{
//This line causes the error
handler->RegisterEventFunc<LogHandler, LogEvent>(this, &LogHandler::Handle);
}
LogHandler::~LogHandler(void)
{
}
void LogHandler::Handle(LogEvent* e)
{
}
試圖編譯這個時候什麼我越來越:
錯誤1個錯誤LNK2019:無法解析的外部符號 「市民:無效__thiscall事件處理程序:: RegisterEventFunc(類LogHandler *,無效(__thiscall LogHandler :: *)(類的LogEvent *))」(?? $ @ RegisterEventFunc @@ VLogHandler @@ VLogEvent (函數「public:__thiscall LogHandler :: LogHandler(class EventHandler *)」(?? 0LogHandler @@ QAE @ PAVEventHandler @@@ Z)中引用的@ EventHandler @@ QAEXPAVLogHandler @@ P81 @ AEXPAVLogEvent @@@ Z @ Z)D: \ Dropbox \ C++ \ D-Tris \ D-Tris \ D-Tris \ LogHandler.obj D-Tris
RegisterEventFunc是如何解決的?它明確實施!?
您需要將模板化方法的實現放入頭文件中。 – v154c1
您的模板函數定義在.cpp文件中嗎?如果是這樣,您需要讓它們可以訪問實例化模板的代碼。在實踐中,最簡單的方法是將它們放在頭文件中。 – juanchopanza
我做什麼?爲什麼?我認爲C++忽略文件,只是將所有東西拼接在一起! – pixartist