2016-10-12 112 views
1

是否可以創建一個模板函數來接收函數指針的可變參數包?函數參數的C++模板包

template<ReturnType (*FN)(), ReturnType (*FNX...)()> 
void run() { 
    ... 
    run<FNX...>(); 
    ... 
} 

我試着放在我能想到的所有地方...,但我不能得到它來編譯。這不支持?

回答

2

你可以使用這個語法,但它看起來很奇怪:

template<void(*... Functions)()> 
void call_all() 
{ 
    initializer_list<int>{(Functions(), 0)...}; 
} 

我別名類型,雖然:

template <typename T> 
using function_ptr = add_pointer_t<enable_if_t<is_function<T>::value,T>>; 

template<function_ptr<void()>... Functions> 
void call_all() 
{ 
    initializer_list<int>{(Functions(), 0)...}; 
} 

您還可以使用輔助類做更多先進的加工:

using fp = function_ptr<string()>; 

template<fp First, fp... Others> 
struct helper 
{ 
    static void run() 
    { 
     helper<First>::run(); 
     helper<Others...>::run(); 
    } 
}; 

template<fp One> 
struct helper<One> 
{ 
    static void run() 
    { 
     DBG(One()); 
    } 
}; 

template<fp... Functions> 
void run() 
{ 
    helper<Functions...>::run(); 
} 

live demo

+0

太棒了,但是我怎樣才能將這個包傳遞給另一個模板(如我的例子)而不將它擴展到實際的調用?我需要逐個調用函數並在調用下一個函數之前檢查它們的返回類型。我的實際模板有兩個參數,第一個功能和其餘部分作爲一個包。 – theduke

+0

@theduke檢查編輯 – krzaq

+0

真棒,謝謝一堆。使用ftw ... – theduke