gpt4 book ai didi

c++ - 使用 boost::function 和 boost::bind 到一个成员变量

转载 作者:行者123 更新时间:2023-11-30 04:24:29 29 4
gpt4 key购买 nike

我正在尝试创建一个允许设置对象成员变量的 boost::function。我已经创建了我能想到的最简单的例子来说明我正在尝试(和失败)的事情。我觉得我掌握了 boost::bind,但我是 boost 的新手,我相信我使用的 boost::function 不正确。

#include <iostream>
#include <Boost/bind.hpp>
#include <boost/function.hpp>

class Foo
{
public:
Foo() : value(0) {}

boost::function<void (int&)> getFcn()
{
return boost::function<void (int&)>( boost::bind<void>( Foo::value, this, _1 ) );
}

int getValue() const { return value; }

private:
int value;
};

int main(int argc, const char * argv[])
{
Foo foo;

std::cout << "Value before: " << foo.getValue();

boost::function<void (int&)> setter = foo.getFcn();
setter(10); // ERROR: No matching function for call to object of type 'boost::function<void (int &)>'
// and in bind.hpp: Called object type 'int' is not a function or function pointer

std::cout << "Value after: " << foo.getValue();

return 0;
}

我在第 28 行遇到错误,我想在其中使用函数将 Foo::value 设置为 10。我是不是把整件事搞错了?我应该只传回一个 int* 或其他东西而不是对所有这些使用 boost 吗?我调用“getFcn()”的原因是因为在我的实际项目中我使用的是消息系统,如果包含我想要的数据的对象不再存在,getFcn 将返回一个空的 boost::function。但我想如果没有找到任何内容,我可以使用 int* 返回 NULL。

最佳答案

boost::bind<void>( Foo::value, this, _1 )在你的代码中本质上是使用 Foo::value作为成员函数。这是错误的。 Foo::value不是函数。

让我们逐步构建它:

class Foo
{
...
boost::function< void (Foo*, int) > getFcn ()
{
return boost::function< void (Foo*, int) >( &Foo::setValue );
}

void setValue (int v)
{
value = v;
}
...
}

int main ()
{
...
boost::function< void (Foo*, int) > setter = foo.getFcn();
setter( &foo, 10);
...
}

所以这里的函数取 this明确反对。让我们使用 boost.bind绑定(bind) this作为第一个参数。

class Foo
{
...
boost::function< void (int) > getFcn ()
{
return boost::bind(&Foo::setValue, this, _1);
}

void setValue (int v)
{
value = v;
}
...
}

int main ()
{
...
boost::function< void (int) > setter = foo.getFcn();
setter( 10);
...
}

(未经测试的代码)

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com