2014-06-12 38 views
0

我有幾個類,每個類都存儲和調用回調函數。回調函數的簽名具有不同的參數和返回類型,但它們都只有一個參數。 (1)提供一個回調函數,它接受一個參數,(2)讓用戶查詢這個函數是否有回調函數被調用,(3)讓用戶檢查傳遞給該函數的參數。到目前爲止,我有這樣的事情:如何編寫通用函數回調測試類?

template<class ReturnType, class ParameterType> class Callable 
{ 
    public: 
     Callable() : m_called(false), m_param() {} 
     ReturnType operator()(ParameterType param) 
     { 
      m_called = true; 
      m_param = param; 
      return Returntype(); 
     } 
     bool Called() { return m_called; } 
     ParameterType Param() { return m_param; } 

    private: 
     bool m_called; 
     ParameterType m_param; 
}; 

這裏有可能使用類可贖回測試類:

#include <boost/function.hpp> 

class ToBeTested 
{ 
    ToBeTested(boost::function<bool (int)> callback) : m_callback(callback) {}; 
    boost::function<bool (int)> m_callback; 

    // (methods which should cause the callback to be called here) 
}; 

下面是一些測試代碼:

#include <boost/bind.hpp> 

int main(int, char**) 
{ 
    Callable<bool, int> callable; 
    ToBeTested tbt(boost::bind(&Callable<bool, int>::operator()); 

    // (tell tbt it should call its callback here) 

    if (callable.Called() 
    { 
     if (EXPECTED_VALUE == callable.Param(); 
     return 0; 
    } 

    return -1; 
} 

這給了我( 1)和(2),但(3)回調函數通過引用獲取其參數時出現問題:Callable :: m_param是引用類型,因此不能默認初始化。我能解決,通過使之可贖回::運算符()取它的參數作爲參考,就像這樣:

ReturnType operator()(ParameterType & param) 

...但隨後回調函數時由值取它的參數,我不能使用類可贖回。

有沒有辦法讓我的測試類工作,而不管回調函數是通過引用接受它的參數,還是我需要寫兩個幾乎相同的測試類?

回答

1

你可以嘗試這樣的事情,在這裏引用實際存儲爲指針:

template<typename T> 
struct ref_to_ptr 
{ 
    typedef T type; 

    static T wrap(T x) { return x; } 
    static T unwrap(T x) { return x; } 
}; 

template<typename T> 
struct ref_to_ptr<T&> 
{ 
    typedef T* type; 

    static T* wrap(T& x) { return &x; } 
    static T& unwrap(T* x) { return *x; } 
}; 

template<class ReturnType, class ParameterType> class Callable 
{ 
    public: 
     Callable() : m_called(false), m_param() {} 
     ReturnType operator()(ParameterType param) 
     { 
      m_called = true; 
      m_param = ref_to_ptr<ParameterType>::wrap(param); 
      return Returntype(); 
     } 
     bool Called() { return m_called; } 
     ParameterType Param() { return ref_to_ptr<ParameterType>::unwrap(m_param); } 

    private: 
     bool m_called; 
     typename ref_to_ptr<ParameterType>::type m_param; 
}; 
+0

謝謝 - 我的同事,我只是學到了一些東西,我們不知道模板可以做的。 :-) – bythescruff

相關問題