2015-07-20 180 views
0

我有一個類應該將某些參數轉發給仿函數,但要做一些額外的工作。如何基於operator()參數推廣一個類?

class SemaphoredEventRouterObserver { 
    My_Semaphore m_semaphore; 
    mywrapper_Function<void (*)(const Event &)> callback; 
    SemaphoredEventRouterObserver(My_Semaphore semaphore, mywrapper_Function<void (*)(const Event &)> o_callback) : m_semaphore(semaphore) { 
     callback = o_callback; 
    } 
    void operator()(const Event & event) { 
     callback(event); 
     semaphone.post(); 
    } 
}  

的問題是我有可能創造幾十個這樣的課程,因爲其他仿函數的參數不同,所以不是接收const Event & event,我無法接受string argint cMyclass abc或其他任何東西。

是否有可能爲此創建模板類?我使用的只是stl,我不能使用boost,儘管我會好奇的看到與boost相關的答案。

+3

關於轉發可變參數模板參數是什麼?看到這裏http://en.cppreference.com/w/cpp/utility/forward –

+1

是的,這就是我一直在尋找 – mvallebr

回答

1

隨着可變參數模板,你可以這樣做:

typename <typename... Ts> 
class SemaphoredRouterObserver { 
    My_Semaphore m_semaphore; 
    mywrapper_Function<void (*)(Ts...)> callback; 
public: 
    SemaphoredEventRouterObserver(My_Semaphore semaphore, 
           mywrapper_Function<void (*)(Ts...)> o_callback) 
    : m_semaphore(semaphore), 
     callback(o_callback) 
    {} 
    void operator()(Ts... args) { 
     callback(args...); 
     semaphone.post(); 
    } 
}; 

然後

using SemaphoredEventRouterObserver = SemaphoredRouterObserver<const Event&>;