强制转换为指向私有类函数的指针

Cast to a pointer to a private class function

本文关键字:类函数 指针 转换      更新时间:2023-10-16

>我有一个围绕以下内容定义的回调:

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。