c++ - 使用 boost::bind 和 boost::function 时遇到问题

标签 c++ class templates boost-bind boost-function

从这个问题开始

How to pass class member functions to a method in a 3rd party library?

快速回顾一下,我需要将指向函数的指针传递给第 3 方库中名为 moveset 的类的构造函数,其定义为

template <class Space>
moveset<Space>::moveset(particle<Space> (*pfInit)(rng*),
          void (*pfNewMoves)(long, particle<Space> &,rng*),
          int (*pfNewMCMC)(long,particle<Space> &,rng*))

库提供的示例是简单地为 pfInit 等定义全局函数,我们称它们为 f、g 和 h。然后从 Controller 类中调用 smc::moveset Moveset(f,g,h);

我已尝试使用 boost:bind 来实现该建议。不幸的是,我正在努力让它发挥作用。

class IK_PFWrapper
{
 public:

 IK_PFWrapper(Skeleton* skeleton, PFSettings* pfSettings) ;
 smc::particle<cv_state> fInitialise(smc::rng *pRng);

... 
} ;

在 Controller 类中

IK_PFWrapper testWrapper (skeleton_,pfSettings_);
boost::function<smc::particle<cv_state> (smc::rng *)>  f = boost::bind(&IK_PFWrapper::fInitialise, &testWrapper,_1) ; 

// the 2nd and 3rd argument will be eventually be defined in the same manner as the 1st
smc::moveset<cv_state> Moveset(f, NULL, NULL); 

由此产生的编译器错误是,

Algorithms\IK_PFController.cpp(88): error C2664: 'smc::moveset<Space>::moveset(smc::particle<Space> (__cdecl *)(smc::rng *),void (__cdecl *)(long,smc::particle<Space> &,smc::rng *),int (__cdecl *)(long,smc::particle<Space> &,smc::rng *))' : cannot convert parameter 1 from 'boost::function<Signature>' to 'smc::particle<Space> (__cdecl *)(smc::rng *)'
with
[
 Space=cv_state
]
and
[
 Signature=smc::particle<cv_state> (smc::rng *)
]
and
[
 Space=cv_state
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

非常感谢任何帮助

最佳答案

参见 demote boost::function to a plain function pointer.

boost::function(您使用 boost::bind 创建的函数不会自动转换为普通的旧函数指针。

我建议创建一个使用 boost::function 的包装器接口(interface),即您的示例(减少为一个参数)看起来像这样:

template <class Space>
moveset<Space>::moveset(boost::function<particle<Space> (rng*)> pfInit)
{
    library_namespace::moveset<Space>(
        pfInit.target<particle<Space>(rng*)>()    // parameter 1
    );
}

创建包装器意味着您只需在一处处理原始函数指针。 希望对您有所帮助,对于代码片段中的任何和所有错误,我们深表歉意!

关于c++ - 使用 boost::bind 和 boost::function 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10011866/

相关文章:

C++ 错误 : Passing 'const' as 'this' array

c++ - 当我们在使用 VS 的 C++ 项目中将库作为附加依赖项引用时,到底发生了什么?

c++ - 删除指针 vector

java - 列出未知枚举的值

python - 类从哪里获得它们的默认 '__dict__' 属性?

java - 如何在两个类之间传递局部变量?

c++ - 是否可以有一个默认的复制构造函数和一个模板化的转换构造函数?

c++ - C++ 是否支持可变长度数组?

c++ - 将枚举值映射到 C++ 中的模板参数

c++ - 与普通 POD 类型相比,如何克服仅包含一个 POD 成员的简单类的性能下降?