Storing boost::bind functions in a std::map

只谈情不闲聊 提交于 2019-12-01 06:02:37

问题


I'm creating a bunch of functions which all effectively do the same thing:

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

where Foo is a class. All fairly simple so far. Now, I effectively want to create a lot of variants on this, but bound to different sets. I then want to store these in a std::map. So, using boost::bind and boost::function, do something like:

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

The problem I'm having is trying to define the type of the map. I thought it would be:

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

But compiling this with MSVC 9.0 gives: error C2582: 'operator =' function is unavailable in 'boost::function<Signature>'.

What exactly should the second template argument to map be?


回答1:


Using boost 1.49 and g++ 4.4.4, I was able to do something very similar. Here is a code snippet.

typedef boost::function< void (SomeType) > CallbackType;

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

I was then able to assign it with the following:

NameCallbackPair somePair(someString, boost::bind(&SomeClass::someMethod, this, _1));

Maybe it's something with MSVC9.




回答2:


Ah I solved it. I was including the wrong header file; instead of:

#include <boost/function.hpp>

I was including things from the boost/function folder like:

#include <boost/function/function_fwd.hpp>



来源:https://stackoverflow.com/questions/9917883/storing-boostbind-functions-in-a-stdmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!