问题:在使用std::funciton的target成员传函数指针时,发现返回结果是空指针。
Because function is a polymorphic wrapper class, it is unaware of the static type of its target callable object, and thus the template parameter TargetType must be explicitly specified.
TargetType shall match the target type, so that typeid(TargetType)==target_type(). Otherwise, the function always returns a null pointer.
怎么理解explicitly specified?
代码如下:
#include <functional>
#include <stdio.h>
class CNone;
void print_total(int (*get_total)(CNone *, int, int), CNone*pobj, int a, int b);
class CNone
{
public:
explicit CNone(int a, int b)
{
m_a = a;
m_b = b;
}
void go()
{
std::function<int(CNone*,int, int)> func = std::bind(&CNone::get_total, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
print_total(*func.target<int (*)(CNone*,int, int)>(), this, m_a, m_b);
}
public:
int get_total(int a, int b)
{
return a + b;
}
private:
int m_a;
int m_b;
};
void print_total(int (*get_total)(CNone *, int, int), CNone *pobj, int a, int b)
{
printf("%d\n", pobj->get_total(a, b));
}
int main()
{
CNone obj_a(1, 2);
obj_a.go();
return 0;
}
引申问题:在需要传入函数指针作为回调函数且回调函数是非静态成员函数的情况下,有没有好的办法?
--
FROM 68.79.41.*