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

Mor*_*rag 29 c++ templates function

在我调用的类中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
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

小智 40

类型pointer-to-member-function不同于pointer-to-function.

函数的类型根据它是普通函数还是某些类的非静态成员函数而不同:

int f(int x);
the type is "int (*)(int)" // since it is an ordinary function
Run Code Online (Sandbox Code Playgroud)

int Mat::f2(int x);
the type is "int (Mat::*)(int)" // since it is a non-static member function of class Mat
Run Code Online (Sandbox Code Playgroud)

注意:如果它是Fred类的静态成员函数,则其类型与普通函数相同: "int (*)(char,float)"

在C++中,成员函数有一个指向对象的隐式参数(成员函数中的this指针).普通的C函数可以被认为具有与成员函数不同的调用约定,因此它们的指针类型(指向成员函数的指针与指向函数的指针)是不同的并且是不兼容的.C++引入了一种新类型的指针,称为指向成员的指针,只能通过提供对象来调用它.

注意:不要试图将指向成员函数的指针"强制转换"为指向函数的指针; 结果是不明确的,可能是灾难性的.例如,指向成员函数的指针不需要包含适当函数的机器地址.正如在上一个示例中所述,如果您有一个指向常规C函数的指针,请使用顶级(非成员)函数或静态(类)成员函数.

更多关于这里这里.

  • 但这并不能解释为什么模板无法解决它。或者我错过了什么? (2认同)

Bar*_*rry 5

这里的问题是,f2是上的方法Mat,而f只是一个自由函数。您不能单独调用f2,它需要一个实例Mat才能对其进行调用。解决此问题的最简单方法可能是:

printf("%d\n", test([=](int v){return this->f2(v);}, 5));
Run Code Online (Sandbox Code Playgroud)

=那里将捕获this,这是你需要叫什么f2