<未解决的重载函数类型>当试图将聚合对象的方法传递给它的类方法 [英] <unresolved overloaded function type> when trying to pass an aggregated object's method to its class method
问题描述
编译我的代码时出现问题。
我有以下结构:
I have some problem compiling my code. I have the following structure:
#include <cstdlib>
using namespace std;
typedef double (*FuncType)(int );
class AnotherClass {
public:
AnotherClass() {};
double funcAnother(int i) {return i*1.0;}
};
class MyClass {
public:
MyClass(AnotherClass & obj) { obj_ = &obj;};
void compute(FuncType foo);
void run();
protected:
AnotherClass * obj_; /*pointer to obj. of another class */
};
void MyClass::compute(FuncType foo)
{
int a=1;
double b;
b= foo(a);
}
void MyClass::run()
{
compute(obj_->funcAnother);
}
/*
*
*/
int main(int argc, char** argv) {
AnotherClass a;
MyClass b(a);
b.run();
return 0;
}
当我尝试编译它时,它给出:
When I try to compile it, it gives:
main.cpp:39:31: error: no matching function for call to ‘MyClass::compute(<unresolved overloaded function type>)’
main.cpp:30:6: note: candidate is: void MyClass::compute(double (*)(int))
这里有什么问题?
p / s / AnotherClass * obj _;
因为我给大图书馆写了一些函数,不能改变它。
p/s/ AnotherClass * obj_;
should stay like that because I write some function to the big library and can't change it.
-------------- working version by Benjamin -------
-------------- working version by Benjamin -------
#include <cstdlib>
using namespace std;
class AnotherClass {
public:
AnotherClass() {};
double funcAnother(int i) {return i*1.0;}
};
struct Foo
{
/*constructor*/
Foo(AnotherClass & a) : a_(a) {};
double operator()(int i) const
{
return a_.funcAnother(i);
}
AnotherClass & a_;
};
class MyClass {
public:
MyClass(AnotherClass & obj) { obj_ = &obj;};
template<typename FuncType>
void compute(FuncType foo);
void run();
protected:
AnotherClass * obj_; /*pointer to obj. of another class */
};
template<typename FuncType>
void MyClass::compute(FuncType foo)
{
int a=1;
double b;
b= foo(a);
}
void MyClass::run()
{
Foo f(*obj_);
compute(f);
}
/*
*
*/
int main(int argc, char** argv) {
AnotherClass a;
MyClass b(a);
b.run();
return 0;
}
非常感谢大家的帮助!
推荐答案
以下函数类将匹配FuncType的签名:
The following function class will match the signature of your FuncType:
struct Foo
{
AnotherClass & a_;
Foo(AnotherClass & a) a_(a) {}
double operator()(int i) const
{
return a_.funcAnother(i);
}
};
将MyClass :: compute更改为模板,因此:
Change MyClass::compute to a template, thusly:
template<typename FuncType>
void MyClass::compute(FuncType foo)
{
int a=1;
foo(a);
}
然后你可以这样调用run:
Then you can call run like this:
void MyClass::run()
{
compute(Foo(*obj_));
}
如果你的编译器支持lambdas(很有可能)你可以放弃函数类并简单定义运行:
If your compiler supports lambdas (and there's a good chance it does), then you can forgo the function class and simply define run like this:
void MyClass::run()
{
auto f = [this](int i) {
return obj_->funcAnother(i);
};
compute(f);
}
这篇关于<未解决的重载函数类型>当试图将聚合对象的方法传递给它的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!