2013-01-21 112 views
10

函數簽名是否有可能實現這樣的事情:作爲模板參數

template<typename Signature> 
class Test 
{ 
    public: 
     //here I want operator() to respect the signature 
}; 

Test<void(int)>   t1; //void operator()(int) 
Test<void(int, float)> t2; //void operator()(int, float) 

返回類型總是void

我想作爲模板參數發送函數簽名。這可能嗎? 我無法使用可變模板,因爲我的編譯器還不支持此功能。

+0

你試圖做什麼?你可以使用函數簽名來實例化一個模板,問題將是執行函數時的參數。參見例如:'boost :: bind'。 – Nim

回答

9
template <class Ty> 
class Test; /* not defined */ 
template <class Ret, class Arg0> 
class Test<Ret(Arg0)> { /* whatever */ } 
template <class Ret, class Arg0, class Arg1> 
class Test<Ret(Arg0, Arg1)> { /* whatever */ } 
template <class Ret, class Arg0, class Arg1, class Arg2> 
class Test<Ret(Arg0, Arg1, Arg2)> { /* whatever */ } 

繼續繁瑣的重複操作,直到您有足夠的參數滿足您的需求。在TR1中,建議各種功能對象模板能夠處理10個參數。這通常是用相當複雜的宏來實現的,以簡化編碼,但它可以通過強力來完成。

12

隨着可變參數模板,你會做一個局部的專業化簽名分解成部分:

template<typename Signature> 
class Test; 
// or the SFINAE-friendlier 
//template<typename Signature> 
//class Test {}; 
// or the hard-error-friendlier 
//template<typename Signature> 
//class Test { 
// static_assert(Bool<false, Signature>{}, 
//     "template argument must be a signature returning void"); 
// // Bool is from http://flamingdangerzone.com/cxx11/2012/05/29/type-traits-galore.html#dependent_boolean 
//}; 

template<typename... Args> 
class Test<void(Args...)> 
{ 
    public: 
     void operator()(Args...) const; 
}; 

沒有你必須做出一個專門爲每個參數的數量可變參數模板。宏可能有助於生成所有這些(Boost.PP,或者Visual Studio用來模擬標準庫中可變參數模板的那些)。