2013-04-05 161 views
17

在我的課程Mat,我希望有一個函數,將另一個函數作爲參數。現在我有以下4個函數,但是在調用print()時出現錯誤。第二行給了我一個錯誤,但我不明白爲什麼,因爲第一行是有效的。唯一的區別是功能f不是類Mat的成員,但是f2是。 故障是:error: no matching function for call to Mat::test(< unresolved overloaded function type>, int)'C++ - <無法解析的重載函數類型>

template <typename F> 
int Mat::test(F f, int v){ 
    return f(v); 
} 

int Mat::f2(int x){ 
    return x*x; 
} 

int f(int x){ 
    return x*x; 
} 

void Mat::print(){ 
    printf("%d\n",test(f ,5)); // works 
    printf("%d\n",test(f2 ,5)); // does not work 
} 

爲什麼會出現這種情況?

+1

'f2'是否是靜態的? – 2013-04-05 18:52:56

+0

嘗試將printf調用更改爲printf(「%d \ n」,test(Mat :: f2,5)); – 2to1mux 2013-04-05 18:57:54

+0

你有多個'f2'超載嗎? – 2013-04-05 18:58:24

回答

3

這裏的問題是f2Mat上的方法,而f只是一個免費的功能。您不能自己撥打f2,需要撥打Mat的實例才能打電話。解決這個問題的最簡單的方法可能是:

printf("%d\n", test([=](int v){return this->f2(v);}, 5)); 

=會有捕捉this,這是你需要調用f2什麼。

+0

由於f2和print都是Mat的成員函數,因此不打印允許在不引用Mat對象的情況下調用f2? – 2to1mux 2013-04-05 19:04:07

+0

哇,這個工程(從原來的代碼調整了一些)。 +1從我 – 2013-04-05 19:04:42

+0

-1。錯誤消息說錯誤發生是因爲函數重載,而不是因爲函數模板的函數調用語法錯誤(這就是你所說的)。 – 2013-04-05 19:06:51

31

pointer-to-member-function的類型不同於pointer-to-function

取決於它是否是一個普通函數或某些類的非靜態成員函數類型的功能是不同的:

int f(int x); 
the type is "int (*)(int)" // since it is an ordinary function 

而且

int Mat::f2(int x); 
the type is "int (Mat::*)(int)" // since it is a non-static member function of class Mat 

注:如果它是Fred類的靜態成員函數,其類型與普通函數類型相同:"int (*)(char,float)"

In C++, member functions have an implicit parameter which points to the object (the this pointer inside the member function). Normal C functions can be thought of as having a different calling convention from member functions, so the types of their pointers (pointer-to-member-function vs pointer-to-function) are different and incompatible. C++ introduces a new type of pointer, called a pointer-to-member, which can be invoked only by providing an object.

NOTE: do not attempt to "cast" a pointer-to-member-function into a pointer-to-function; the result is undefined and probably disastrous. E.g., a pointer-to-member-function is not required to contain the machine address of the appropriate function. As was said in the last example, if you have a pointer to a regular C function, use either a top-level (non-member) function, or a static (class) member function.

更多關於Herehere

+0

但這並不能解釋爲什麼模板無法解決它。或者我錯過了什麼? – 2013-04-05 20:36:48

+0

@LuchianGrigore這就是我的理解。編譯器需要一個提供'調用操作符'的類型,或者查看它是否能夠找到一個匹配Mat :: Test可以訪問的'int f(int)'的函數。根據上面的描述,'指向成員函數的指針與指向函數的指針是不同的和不兼容的'。所以它不會匹配'this-> f2'作爲一個函數。這只是我的理解。在今天之前,我甚至都不知道:) – 2013-04-05 20:50:50

+0

鏈接似乎已經死亡。 – derM 2017-09-20 12:39:10

相關問題