以下代码片段编译&适用于Visual Studio 2010。
现在我想改进一件小事,但我找不到办法。我尝试了一些模板模板技巧等,但无济于事。
我想要以下代码行:
Sender.AttachListener<XSelectionChanged, TestListener, &TestListener::OnSelectionChanged>(Listener);
看起来像
Sender.AttachListener<&TestListener::OnSelectionChanged>(Listener);
也就是说,我向AttachListener模板提供了一个常量“void(TClass :: * TMethod)(TEvent&amp; _rEvent)”。从这个常量的类型我想得到TClass和TEvent类型。
这可能吗?如果是,怎么样?
-Matthias
代码:
#include <stdio.h>
#include <tchar.h>
#include <map>
#include <iostream>
struct XEvent
{};
struct XSelectionChanged : public XEvent
{};
struct XValueChanged : public XEvent
{};
template<typename TEvent, typename TClass>
struct TMethodType
{
typedef void (TClass::*MethodType)(TEvent& _rEvent);
};
template<typename TEvent, typename TClass, void (TClass::*TMethod)(TEvent& _rEvent)>
struct TBoundMethod
{
static void Dispatch(TEvent& _rEvent, TClass* _pInstance)
{
(_pInstance->*TMethod)(_rEvent);
}
};
class CEventHost
{
public:
template <typename TEvent, typename TClass, void (TClass::*TMethod)(TEvent& _rEvent)>
void AttachListener(TClass& _rInstance)
{
TBoundMethod<TEvent, TClass, TMethod>::Dispatch( TEvent(), &_rInstance );
//m_EventHost.Attach( &TBoundMethod<TClass, TEvent, TMethod>::Dispatch, &_rInstance );
}
template <typename TEvent>
void SendEvent(TEvent& _rEvent)
{
//m_EventHost.Send( _rEvent );
}
protected:
//SHost m_EventHost;
};
class TestListener
{
public:
void OnSelectionChanged(XSelectionChanged& _rEvent)
{
printf("Selection changed!\n");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CEventHost Sender, Sender2;
TestListener Listener;
Sender.AttachListener<XSelectionChanged, TestListener, &TestListener::OnSelectionChanged>(Listener);
Sender.SendEvent(XSelectionChanged());
Sender2.SendEvent(XSelectionChanged());
Sender.SendEvent(XValueChanged());
getchar();
return 0;
}
答案 0 :(得分:1)
是的,使用元函数来提取TClass和TEvent,如下所示:
template<typename T>
class GetSignature {};
template<typename TClass, typename TEvent>
class GetSignature <void (TClass::*)(TEvent&)>
{
public:
typedef TClass Class;
typedef TEvent Event;
};
template <typename T>
void AttachListener(typename GetSignature<T>::Class& _rInstance)
{
typedef GetSignature<T> Signature;
typedef void (TClass::*MethodType)(TEvent&);
TBoundMethod<
typename Signature::Event,
typename Signature::Class,
MethodType
>::Dispatch( TEvent(), &_rInstance );
//m_EventHost.Attach( &TBoundMethod<TClass, TEvent, TMethod>::Dispatch, &_rInstance );
}
警告:未经测试; - )
答案 1 :(得分:0)
您确实需要std::function
或boost::function
。