将boost::bind函数存储在std::map中

3

我正在创建一组函数,这些函数的实际作用都相同:

long Foo::check(long retValue, unsigned toCheck, const std::set<unsigned>& s)
{
    auto it = s.find(toCheck);
    return (it == s.end()) ? -retValue : retValue;
}

其中Foo是一个类。到目前为止都很简单。现在,我想要在不同的集合上创建大量变体,并将它们绑定到不同的集合。然后,我希望将这些变体存储在std::map中。因此,使用boost::bind和boost::function,可以执行以下操作:

void Foo::addToMap(unsigned option, const std::set<unsigned>& currentSet)
{
    someMap[option] = boost::bind(&Foo::check, this, _1, _2, currentSet);
}

我遇到的问题是定义地图类型。我认为应该是这样的:

std::map<unsigned, boost::function<long (long, unsigned)> > someMap;

使用MSVC 9.0编译会得到以下错误:error C2582: 'operator =' function is unavailable in 'boost::function<Signature>'

在map的第二个模板参数中应该填什么?


你尝试过用boost::ref或者其他类似的方式来包装set参数(绑定)吗?引用是不可赋值的。 - Cheers and hth. - Alf
@Cheersandhth.-Alf 尝试使用 boost::cref(currentSet) 进行封装,但仍然出现完全相同的错误。如果我传递非 const 或非 const 值,情况也是一样的... - Yuushi
1
哦,该死。请尝试使用最小程序重现问题,并发布完整代码。 - Cheers and hth. - Alf
@Cheersandhth.-Alf 感谢您。通过创建一个最小的程序,我意识到自己没有包含正确的头文件,所以您间接地帮助了我解决了这个问题。 - Yuushi
2个回答

0
啊,我解决了。我包含了错误的头文件;应该是:

#include <boost/function.hpp>

我包含了 boost/function 文件夹中的东西,比如:

#include <boost/function/function_fwd.hpp>


0
使用boost 1.49和g++ 4.4.4,我能够做类似的事情。这里是一段代码片段。
typedef boost::function< void (SomeType) > CallbackType;

std::pair<std::string, CallbackType> NameCallbackPair;

我随后能够使用以下方式分配它:
NameCallbackPair somePair(someString, boost::bind(&SomeClass::someMethod, this, _1));

也许是与 MSVC9 有关的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接