#include<iostream>
template<typename T>
class testClass {
public:
T a;
};
template<typename T>
void testFunc( void *a ) {
testClass<T> *tempClass = reinterpret_cast<testClass<T> *>(a);
tempClass->a++;
}
int main() {
void (*foo)(void *);
foo = testFunc<int>;
testClass<int> a;
a.a = 100;
std::cerr << "Before = " << a.a << "\n";
foo(&a);
std::cerr << "After = " << a.a << "\n";
return 0;
}
这个模板函数 testFunc 可以作为函数指针安全地传递给C函数吗?我不清楚C ++如何能够为函数指针分配正确的内存地址。混淆是因为我无法编译将类成员函数作为函数指针参数传递的相同代码。
答案 0 :(得分:0)
方法的要点是,为了访问方法指针,编译器会要求您提供调用此方法的对象,以便在访问方法时自动填充this
成员。
在这里,你提到一个简单的函数指针,所以你不需要提供任何对象,所以是的,你可以认为它是安全的。