gpt4 book ai didi

c++ - <未解析的重载函数类型>

转载 作者:IT老高 更新时间:2023-10-28 12:47:18 35 4
gpt4 key购买 nike

在我的类(class) Mat ,我想要一个以另一个函数作为参数的函数。现在我有下面的 4 个函数,但是在调用 print() 时出现错误。第二行给了我一个错误,但我不明白为什么,因为第一行有效。唯一的区别是函数 f不是该类的成员 Mat , 但是 f2是。失败是: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
}

为什么会这样?

最佳答案

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 .

关于c++ - <未解析的重载函数类型>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15841338/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com