#include <iostream>
struct A {
explicit A(int a) : _a(a) {};
int _a;
};
struct ClassFunction {
ClassFunction(std::shared_ptr<A> myA) : _myA(myA) {}
double operator() (int &x,
int &g) {
return 1.0
+ static_cast<double>(_myA->_a); // offending line
}
static double wrap(int x, int g, void *data) {
return (*reinterpret_cast<ClassFunction*>(data)) (x,g);
}
std::shared_ptr<A> _myA;
};
int main() {
int x = 1;
int g;
auto myA = std::shared_ptr<A>(new A(int(20)));
ClassFunction myClassFunction(myA);
std::cout << ClassFunction::wrap(x,g,NULL) << std::endl;
return 0;
}
我尝试创建一个以ClassFunction
为参数的函数对象类std::shared_ptr<A>
,然后通过static
成员函数ClassFunction::wrap
调用该参数。
如果我将A
的数据成员作为myA->_a
访问,则该程序无法运行(但它会在没有任何投诉的情况下进行编译)。
我如何使这项工作?
答案 0 :(得分:1)
尝试以下方法:
std::cout << ClassFunction::wrap(x, g, &myClassFunction) << std::endl;
的reinterpret_cast&LT;当数据指向ClassFunction类的实例时,ClassFunction *&gt;(data)适用。