Search code examples
c++static-methodspointer-to-member

Want a static member function to call a member variable of the same class


headerfile.h

class A
{
  cv::Mat depthimagemouse;
  std::string m_winname;

public:

  A(const std::string &winname, const cv::Mat depth_clean);
  static void onMouse( int evt, int x, int y, int flags, void* param );
};

cppfile.cpp

A::A(const std::string &winname, const cv::Mat depth_clean)
    : m_winname(winname), depthimagemouse(depth_clean)
{
//something..
}

void A::onMouse( int event, int x, int y, int flags, void* param )
{
//Here I want to use depthimagemouse member variable (and other members..)
}

My question is how can I use depthimagemouse variable in onMouse method?


Solution

  • I'd be surprised if the library didn't explain this somewhere in its documentation, but anyway. This is standard procedure when you're using callbacks that don't support member functions, but you still need a way to access member data. So, you do the following:

    • Pass a reference to the instance as your user data pointer param (or a member thereof) when registering the callback.
    • Cast this back to the concrete type to access its members. A class static function has full access to all members of its class, via a provided instance.

    So, you can do it this way:

    auto &that = *static_cast<A *>(param); // <= C++03: use A &that
    // Cast to const A if you want, or use a pointer, or etc.
    std::cout << that.depthimagemouse << std::endl;
    

    Or it's often nicer syntactically to immediately despatch to a member function and let it do everything:

    static_cast<A *>(param)->doRestOfStuff(evt, x, y, flags);
    // Include a const in the cast if the method is const
    

    Or anywhere in between.