简体   繁体   English

将 std::function 绑定到 C++ 中的成员函数?

[英]Binding a std::function to a member function in c++?

I'm working with Open3D library using the following function :我正在使用以下函数使用 Open3D 库:

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.如果我从 main 调用此函数并将该函数放在同一个main.cpp文件中,我已经设法让它正常工作。 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:这是从this post派生,但给了我以下错误:

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没有合适的用户定义转换从“std::_Binder<std::_Unforced, bool (MeshHandler::*)(open3d::visualization::Visualizer *vis), MeshHandler &>”到“std::function<bool ( open3d::visualization::Visualizer *)>" 存在

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.MeshHandler::UpdateMesh()函数中,我想访问类实例的其他成员。

Turns out you need to use std::placeholders in your std::bind function.原来你需要在std::bind函数中使用std::placeholders 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.有关更多信息,请参阅std::bind文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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