将赋值运算符绑定到 boost::function 对象

binding an assignment operator to a boost::function object

本文关键字:function 对象 boost 赋值运算符 绑定      更新时间:2023-10-16

我有一个Visual Studio 2008 C++03项目,我想使用boost::function对象来设置指针的值。像这样:

boost::function< void( int* ) > SetValue;
boost::function< int*() > GetValue;
int* my_value_;
SetValue = boost::bind( my_value_, _1 ); // how should this look?
GetValue = boost::bind( my_value_ ); // and this?
int v;
SetValue( &v );
assert( my_value_ == &v );
int* t = GetValue();
assert( t == my_value_ );

有没有办法做到这一点,或者我需要一个中间函数,例如:

void DoSetValue( int* s, int* v ) { s = v; };
SetValue = boost::bind( DoSetValue, my_value_, _1 );

谢谢

使用 Boost.Lambda 库:

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
int main()
{
    boost::function<void(int*)> SetValue = (boost::lambda::var(my_value) = boost::lambda::_1);
    boost::function<int*()> GetValue = boost::lambda::var(my_value);
}

您可以在其文档中找到有关使用变量的更多信息。

您的第一次尝试将不起作用,因为bind()需要一个函数(或函子(,但您正在传递一个数据指针,因此您需要提供一个函数来完成您寻找的工作。

注意:如果使用 C++11,则可以使用 lambda,以避免创建命名函数

注意:您需要取消引用DoSetValue中的指针或使用引用(在这种情况下,您还需要更改SetValue的声明(——否则更改将在函数调用之外不可见

void DoSetValue( int& s, int& v ) { s = v; }; 

要使bind以这种方式工作,您需要一个指向operator=( int* )的指针。当然,没有这样的事情,所以你需要一个中间函数。

如果你可以使用lambdaphoenix,有一些方法可以制作一个函数对象,将某些东西分配给其他东西。这取决于您使用的库,但它看起来有点像这样:

bl::var( my_value_ ) = bl::_1;