C++ - <无法解析的重载函数类型>
在我的课程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
}
为什么会出现这种情况?
这里的问题是f2
是Mat
上的方法,而f
只是一个免费的功能。您不能自己拨打f2
,需要拨打Mat
的实例才能打电话。解决这个问题的最简单的方法可能是:
printf("%d\n", test([=](int v){return this->f2(v);}, 5));
的=
会有捕捉this
,这是你需要调用f2
什么。
由于f2和print都是Mat的成员函数,因此不打印允许在不引用Mat对象的情况下调用f2? – 2to1mux 2013-04-05 19:04:07
哇,这个工程(从原来的代码调整了一些)。 +1从我 – 2013-04-05 19:04:42
-1。错误消息说错误发生是因为函数重载,而不是因为函数模板的函数调用语法错误(这就是你所说的)。 – 2013-04-05 19:06:51
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.
但这并不能解释为什么模板无法解决它。或者我错过了什么? – 2013-04-05 20:36:48
@LuchianGrigore这就是我的理解。编译器需要一个提供'调用操作符'的类型,或者查看它是否能够找到一个匹配Mat :: Test可以访问的'int f(int)'的函数。根据上面的描述,'指向成员函数的指针与指向函数的指针是不同的和不兼容的'。所以它不会匹配'this-> f2'作为一个函数。这只是我的理解。在今天之前,我甚至都不知道:) – 2013-04-05 20:50:50
链接似乎已经死亡。 – derM 2017-09-20 12:39:10
'f2'是否是静态的? – 2013-04-05 18:52:56
尝试将printf调用更改为printf(“%d \ n”,test(Mat :: f2,5)); – 2to1mux 2013-04-05 18:57:54
你有多个'f2'超载吗? – 2013-04-05 18:58:24