[英]Template of template parameter with GCC
我正在嘗試使用模板模板作為參數,當我用clang編譯時一切正常,但是當我嘗試使用GCC 4.8時,我有以下錯誤:
不能從非模板類型'DamageAnimationSystem'中推斷出'TReceiver'的模板
這是我的情況:我有一個程序,類可以為某些類型的事件訂閱事件管理器,但不是全部。
為此,我從具有特定類型的類繼承:
class DamageAnimationSystem : public Receiver<DamageEvent>,
public Receiver<HealthEvent>
在這里,我的類將偵聽“DamageEvent”和“HealthEvent”,因此我需要為此類事件聲明虛擬方法:
DamageAnimationSystem::onEvent( const DamageEvent& event ) {}
DamageAnimationSystem::onEvent( const HealthEvent& event ) {}
我需要訂閱此活動:
DamageAnimationSystem::DamageAnimationSystem()
{
eventManager->subscribe<DamageEvent>(this);
eventManager->subscribe<HealthEvent>(this);
}
正如我之前所說的,當我使用Clang時一切正常,但是當我使用GCC時,我得到了上面給出的錯誤。
這就是我所做的:
接收器:
class EBaseReceiver
{
protected:
static std::size_t nextId;
};
template <typename TEventData>
class Receiver : public EBaseReceiver
{
friend class EventManager;
public:
virtual void onEventReceive( const TEventData& event ) = 0;
static std::size_t getId() { return ID; }
private:
static std::size_t ID;
};
事件:
struct BaseEvent
{
protected:
static std::size_t nextId;
};
template <typename T>
struct Event : public BaseEvent
{
static std::size_t getId() { return ID; }
static std::size_t ID;
};
**And finally the event manager:**
template< class TEvent, template<class> class TReceiver>
void EventManager::subscribe( TReceiver<TEvent>* receiver );
{
const std::size_t eventId = TEvent::getId();
this->subscribers[eventId].push_back(receiver);
}
我已經在線模擬測試結果: https : //ideone.com/vZZhqN
非常感謝你的幫助!
PS:我需要與GCC兼容,因為我需要在Android NDK中使用此代碼,並且線程在最后一個NDK上不能與clang一起使用。
我正在嘗試使用std :: function和std :: bind的另一個方法:
接收器:
class Receiver {};
事件:
template <typename T>
struct Event : public BaseEvent
{
friend class EventManager;
static std::size_t getId() { return ID; }
private:
typedef std::function<void( const T& event )> EventCallback;
static std::size_t ID;
static std::vector<EventCallback> listeners;
};
** 事件管理器 **
////////////////////////////////////////////////////////////
template <typename TEvent>
void emit( const TEvent& event )
{
const auto& listeners = TEvent::listeners;
for( const auto& listener : listeners )
listener(event);
}
////////////////////////////////////////////////////////////
template< class TEvent, class TReceiver>
void subscribe( TReceiver* receiver )
{
TEvent::listeners.push_back(std::bind( &TReceiver::onEventReceive, receiver, std::placeholders::_1));
}
我在std :: bind上遇到以下錯誤:
No matching function for call to 'bind'
Candidate template ignored: couldn't infer template argument '_Fp'
Candidate template ignored: couldn't infer template argument '_Rp'
再次感謝!
以下編譯(不要鏈接): https : //ideone.com/EheCok
我通過這種方式顯式模板參數:
eventManager.subscribe<HealthEvent, ::Receiver>(this);
eventManager.subscribe<DamageEvent, ::Receiver>(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.