简体   繁体   中英

Binding a std::function to a member function in c++?

I'm working with Open3D library using the following function :

bool open3d::visualization::DrawGeometriesWithAnimationCallback 
(   
const std::vector< std::shared_ptr< const geometry::Geometry >> &   geometry_ptrs,
std::function< bool(Visualizer *)>  callback_func,
const std::string &     window_name = "Open3D",
int     width = 640,
int     height = 480,
int     left = 50,
int     top = 50 
)

I have managed to get it working, if I call this function from my main and having the function in the same main.cpp file. However, I would like to point to a class member function instead. This is what I got so far:

#include "WorkDispatcher.h"

int main(int argc, char* argv[]) 
{
    // setup of the needed classes I want to point to
    WorkDispatcher dispatcher;
    dispatcher.Initialize();
    dispatcher.m_MeshHandler.m_Mesh = open3d::geometry::TriangleMesh::CreateBox();
    dispatcher.Work();

    // here is the described issue
    std::function<bool(open3d::visualization::Visualizer*)> f = std::bind(&MeshHandler::UpdateMesh, dispatcher.m_MeshHandler);
    open3d::visualization::DrawGeometriesWithAnimationCallback({ dispatcher.m_MeshHandler.m_Mesh }, f, "Edit Mesh", 1600, 900);
    
    dispatcher.Stop();
    return 0;

}

This is derived from this post , but gives me the following error:

no suitable user-defined conversion from "std::_Binder<std::_Unforced, bool (MeshHandler::*)(open3d::visualization::Visualizer *vis), MeshHandler &>" to "std::function<bool (open3d::visualization::Visualizer *)>" exists

I'm not quite sure how to resolve this issue. Within the MeshHandler::UpdateMesh() function I would like to access other members of the class instance.

Turns out you need to use std::placeholders in your std::bind function. The following code works:

std::function<bool(open3d::visualization::Visualizer*)> f = std::bind(&MeshHandler::UpdateMesh, dispatcher.m_MeshHandler, std::placeholders::_1);
open3d::visualization::DrawGeometriesWithAnimationCallback({ dispatcher.m_MeshHandler.m_Mesh }, f, "Edit Mesh", 1600, 900);

Seestd::bind documentation for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM