2011-11-14 45 views
0

有沒有辦法使用typedef作爲模板函數的參數?或者一種將類型定義爲參數的方法?是否可以在模板化函數簽名中使用typedef?

比方說,我想給一個函數指針傳遞給這個函數:

template<typename C, typename ...Args> 
void test(typedef void (C::*functor)(Args... args) functor f) 
{ 
    f(args...); 
} 
+0

雞蛋裏挑骨頭:我知道這很令人困惑,但指向一個成員函數既不是一個函數指針,也不是一個指針。 (有趣的相關閱讀:https://blogs.msdn.com/themes/blogs/generic/post.aspx?WeblogApp=oldnewthing&y=2004&m=02&d=09&WeblogPostID=70002&GroupKeys=) –

回答

3

不,您不能在參數中創建typedef。如果你的目標是避免重複在函數體參數的類型,你可以使用decltype

template<typename C, typename ...Args> 
void test(void (C::*f)(Args...)) 
{ 
    typedef decltype(f) functor; 
} 
+0

好的,我明白了,謝謝 – codablank1

0

但是,爲什麼甚至想,當你可以這樣寫:

template<typename C, typename ...Args> 
void test(void (C::*f)(Args...), Args... args) 
{ 
    C c; //f is a member function, so need an instance of class 
    (c.*f)(args...); //call the function using the instance. 
} 

或者,您可以將該實例與參數一起傳遞,或者執行其他操作。我認爲這只是一個概念驗證,而在真實的代碼中則是另一回事。

相關問題