c ++ - <未解析的重载函数类型> [英] c++ - <unresolved overloaded function type>
问题描述
在我的类Mat中,我想有一个函数,它接受另一个函数作为参数。现在我有这4个函数,但是我在调用print()时遇到错误。第二行给我一个错误,但我不明白为什么,如果第一个工作。唯一的区别是函数f不是类Mat的成员,而是f2。
它说:错误:没有匹配的函数调用'Mat :: test(<未解决的重载函数类型>,int)'
In my class called Mat, I want to have a function, which takes another function as a parameter. Right now I got these 4 functions, but I get an error in when calling print(). The second line gives me an error, but I don't understand why, if the first one works. The only difference is function f is not a member of the class Mat, but f2 is. It says: 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\n",test(f ,5)); // works
printf("%d\n",test(f2 ,5)); // does not work
}
为什么会发生这种情况?
Why does this happen?
推荐答案
指针的类型-member-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(*) ,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
函数可以被认为具有来自成员函数的不同的调用约定
,因此它们的指针的类型
(指针到成员函数vs指针到函数)不同,
不兼容。 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.
有关此此处和< a href =http://www.parashift.com/c++-faq-lite/addr-of-memfn.html>此处。
这篇关于c ++ - <未解析的重载函数类型>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!