我正在尝试编写一个在编译时链接到函数指针的包装函数,因此我编写了以下代码,它在C ++ 11中运行得非常好:
#include <iostream>
template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
//do something else here
return (*func)(args...);
}
double add(double a, double b){
return a+b;
}
int main(){
std::cout << callfunc<decltype(&add), &add>(2.0, 3.0) << "\n";
}
但是,如果我尝试使用像这样的成员函数做同样的事情
#include <iostream>
template<typename Fn, Fn func, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Args&&... args){
//do something else here
return (*func)(args...);
}
class testclass {
public:
double testadd(double a, double b);
void run();
};
double testclass::testadd(double a, double b){
return a+b;
}
void testclass::run(){
std::cout <<
callfunc<decltype(&testclass::testadd), &testclass::testadd>(2.0, 3.0)
// ^^^^^ this won't compile! ^^^^
<< "\n";
}
int main(){
testclass obj;
obj.run()
}
我收到以下编译错误:
error: indirection requires pointer operand ('double (testclass::*)(double,double)' invalid) return (*func)(args...);
我做错了什么?
答案 0 :(得分:2)
要调用非静态成员函数,您需要一个有效的实例指针。以下是您的代码的修改版本:
#include <iostream>
template<typename Fn, Fn func, typename Class, typename... Args>
typename std::result_of<Fn(Args...)>::type callfunc(Class* instance, Args&&... args){
return (instance->*func)(args...);
}
class testclass {
public:
double testadd(double a, double b);
void run();
};
double testclass::testadd(double a, double b){
return a + b;
}
void testclass::run(){
std::cout <<
callfunc<decltype(&testclass::testadd), &testclass::testadd>(this, 2.0, 3.0)
<< "\n";
}
int main(){
testclass obj;
obj.run();
}