問題描述
在我的名為 Mat
的類中,我想要一個將另一個函數作為參數的函數.現在我有下面的 4 個函數,但是在調用 print() 時出現錯誤.第二行給了我一個錯誤,但我不明白為什么,因為第一行有效.唯一的區別是函數 f
不是 Mat
類的成員,但 f2
是.失敗是:error: no matching function for call to Mat::test( < unresolved overloaded function type>, int)'
In my class called Mat
, I want to have a function which takes another function as a parameter. Right now I have the 4 functions below, but I get an error in when calling print(). The second line gives me an error, but I don't understand why, since the first one works. The only difference is function f
is not a member of the class Mat
, but f2
is.
The failure is: error: no matching function for call to Mat::test( < unresolved overloaded function type>, int)'
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
",test(f ,5)); // works
printf("%d
",test(f2 ,5)); // does not work
}
為什么會發生這種情況?
Why does this happen?
推薦答案
pointer-to-member-function
的類型與 pointer-to-function
不同.
函數的類型根據是普通函數還是某個類的非靜態成員函數而不同:
The type of a function is different depending on whether it is an ordinary function or a non-static member function of some class:
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)"
Note: if it's a static member function of class Fred, its type is the same as if it were an ordinary function: "int (*)(char,float)"
在 C++ 中,成員函數有一個隱式參數指向對象(成員函數內的 this 指針).正常 C函數可以被認為具有不同的調用約定來自成員函數,所以它們的指針類型(指向成員函數的指針與指向函數的指針)不同并且不兼容. C++ 引入了一種新的指針類型,稱為成員指針,只能通過提供對象調用.
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.
注意:不要試圖將指向成員函數的指針強制轉換"為函數指針;結果是不確定的,可能是災難性的.例如,指向成員函數的指針不需要包含相應函數的機器地址. 正如上次所說例如,如果您有一個指向常規 C 函數的指針,請使用頂級(非成員)函數,或靜態(類)成員函數.
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.
更多關于這個這里和這里.
這篇關于c++ - <未解析的重載函數類型>的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!