强制转换为指向私有类函数的指针
Cast to a pointer to a private class function
>我有一个围绕以下内容定义的回调:
namespace {
bool OnEvent(int16_t* buffer, size_t num_samples, void* ptr_to_class) {
return reinterpret_cast<MyClass*>(ptr_to_class)->EventHandler(buffer, num_samples);
}
} // anonymous namespace
但是,为了能够在此回调中调用EventHandler()
,我必须将其定义为公共。我想知道是否有办法将其定义为私有成员并在回调中将指针传递给这个私有函数?
类似的东西
namespace {
bool OnEvent(int16_t* buffer, size_t num_samples, void* ptr_to_function) {
return reinterpret_cast<MyClass::EventHandler*>(ptr_to_function)(buffer, num_samples);
}
} // anonymous namespace
这行不通。任何帮助将不胜感激。
您可以使用 std::bind 来授予对私有函数的访问权限:
class PFunctor{
int m_value=0;
int getValue(){
return m_value;
}
void setValue(int val){
m_value = val;
}
public:
std::function<int()> getPFunc(){
return std::bind(&PFunctor::getValue,this);
}
auto setPFunc(){
return std::bind(&PFunctor::setValue,this, std::placeholders::_1);
}
};
...
PFunctor tfunctor;
auto getfunc = tfunctor.getPFunc();
auto setfunc = tfunctor.setPFunc();
std::cout << getfunc() << std::endl;
setfunc(-100);
std::cout << getfunc() << std::endl;
我包括了显式的 std::function use 和 auto use。
相关文章:
- 带有类的函数指针
- 通过函数指针定义类范围之外的方法
- 从类成员函数到类 C 函数指针的转换
- 返回类函数指针 c++
- 在映射中存储模板类函数指针
- 模板类函数指针类型别名
- C++ - 基类函数指针调用的替代方法
- 是否可以使用包含{sub,super}类函数指针的回调表
- 通过基类函数指针调用派生类
- 类函数指针作为参数
- C++中抽象成员和类函数指针的深层复制构造函数
- 将类函数指针传递到另一个类
- 通过 VC++ 中的类 A 函数指针调用类成员函数(类 B)
- 没有为c++类函数指针注册python类
- 如何在另一个类或结构中使用类函数指针
- 如何:类函数指针(c++)
- 使用基类函数指针访问派生类成员函数
- 调用与父类函数指针同名的函数
- boost绑定类函数指针
- 如何从另一个类的函数中获取非静态函数的类函数指针?