2016-09-20 63 views
4

也許是流感,或者我只是愚蠢的,但我不明白的一部分this烏鴉框架代碼。我的內部C++解析器失敗。無法理解這個模板參數

template <typename MW> 
struct check_before_handle_arity_3_const 
{ 
template <typename T, 
    //this line 
    void (T::*)(int, typename MW::context&) const = &T::before_handle 
    > 
    struct get 
    { }; 
}; 

我知道這是模板聲明中的模板參數。它看起來可能是一些lambda或函數指針類型參數......但是,我不確定。 有人可以解釋這一行嗎?

更新: 探索新獲得的知識深度 - 給出了答案後 - 使我這個摘錄從一個偉大的book

模板可以接受一個指向函數作爲無類型模板 參數。 (在本書中,大多數情況下,非類型模板參數是 整數值。)[...]使用指向函數的指針作爲非類型 模板參數意味着我們不再需要將其存儲在地圖中。 這個重要的方面需要徹底的理解。我們 不需要存儲指向某個函數的指針的原因是編譯器有關於它的靜態知識 。因此,編譯器可以在蹦牀代碼中對 函數地址進行硬編碼。

所以,現在我知道使用這種技術的原因之一。

+1

它是'T'的成員函數指針。順便說一句,你忘了問一個問題。 –

+2

我的英語語法分析器未能看到問號。你有什麼問題?這是否是C++?無論是在殺你嗎? –

+0

此更新是否符合問題? – strangeqargo

回答

9

void (T::*)(int, typename MW::context&) const是非型template parameter。 這是一個指向T成員函數的指針。使用= &T::before_handle,其默認值設置爲&T::before_handle

2

我使用這種技術的原因是爲了支持2種處理程序格式: https://github.com/ipkn/crow/blob/master/include/middleware.h#L17

check_before_handle_arity_3_const用在這裏:

template <typename T> 
    struct is_before_handle_arity_3_impl 
    { 
     template <typename C> 
     static std::true_type f(typename check_before_handle_arity_3_const<T>::template get<C>*); 

     template <typename C> 
     static std::true_type f(typename check_before_handle_arity_3<T>::template get<C>*); 

     template <typename C> 
     static std::false_type f(...); 

    public: 
     static const bool value = decltype(f<T>(nullptr))::value; 
    }; 

隨着SFINAE,is_before_handle_arity_3_impl<T>::value確定我們是否可以調用處理程序與3個參數與否。通過使用std::enable_if,Crow可以調用正確的處理程序: https://github.com/ipkn/crow/blob/master/include/http_connection.h#L110