2010-12-06 88 views
25

如何獲得一個方法指針的方法的特定超載:C++重載方法指針

struct A { 
    void f(); 
    void f(int); 
    void g(); 
}; 

我知道

&A::g 

是指向g。但是,如何獲得指向ff(int)的指針?

回答

32
(void (A::*)()) &A::f 
(void (A::*)(int)) &A::f 

函數指針和成員函數指針有這個特性 - 重載可以通過結果分配或者轉換來解決。

如果函數是靜態的,那麼你應該把他們當作普通的功能:

(void (*)()) &A::f; 
(void (*)(int)) &A::f; 

甚至

(void (*)()) A::f; 
(void (*)(int)) A::f; 
+0

謝謝!如果成員函數是靜態的呢? (我得到錯誤:沒有上下文類型信息的重載函數的地址) – 2010-12-06 08:54:47

+0

@Neil:看我的編輯 – 2010-12-06 08:57:45

9

你一定要投的&A::f結果,以消除不確定性:

static_cast<void (A::*)()>(&A::f); // pointer to parameterless f 
static_cast<void (A::*)(int)>(&A::f); // pointer to f which takes an int 
5

感謝Stefan Pabst提出的以下想法:wh呃他在ACCU 2015的一個五分鐘的閃電演講中提出了我的問題。我用標籤類型對它進行了擴展,以允許通過cv限定符和/或引用限定符來解決重載,並且使用C++ 17變量模板來避免輸入額外的對另有要求的括號。

該解決方案的工作原理與基於轉換的答案基本相同,但是您不必重新聲明該函數的返回類型,或者在成員函數的情況下,該函數是類的名稱成員,因爲編譯器能夠推斷出這些東西。

bool free_func(int, int) { return 42; } 
char free_func(int, float) { return true; } 
struct foo { 
    void mem_func(int) {} 
    void mem_func(int) const {} 
    void mem_func(long double) const {} 
}; 

int main() { 
    auto f1 = underload<int, float>(free_func); 
    auto f2 = underload<long double>(&foo::mem_func); 
    auto f3 = underload<cv_none, int>(&foo::mem_func); 
    auto f4 = underload<cv_const, int>(&foo::mem_func); 
} 

實施underload模板的代碼是here