微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用 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 
)

如果我从 main 调用函数并将该函数放在同一个 main.cpp 文件中,我已设法使其正常工作。 但是,我想改为指向类成员函数。 这是我目前得到的:

#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 post 派生的,但给了我以下错误

没有合适的用户定义的从“std::_Binder<:_unforced bool meshhandler>”到“std::function”的转换" 存在

我不太确定如何解决这个问题。在 MeshHandler::UpdateMesh() 函数中,我想访问类实例的其他成员。

解决方法

事实证明您需要在 std::placeholders 函数中使用 std::bind。 以下代码有效:

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);

有关详细信息,请参阅 std::bind 文档。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。