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

2021-12-13 00:00:00 function templates c++

在我的名为 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.

更多关于这个这里和这里.

相关文章