c++ - 比较存储为 boost::function 的函数指针

标签 c++ boost boost-function

我有一个 boost::function 对象的列表,我正试图找到一个特定的对象,以便我可以将它从列表中删除。实际上,一个函数已注册(推送到 vector 上),我希望能够注销它(搜索 vector 并删除匹配的函数指针)。这是代码:

#include <string>
#include <vector>

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>

class DummyClass
{
public:
    std::string Data;
};
typedef boost::shared_ptr<DummyClass> DummyClassPtrType;

class UpdaterClass
{
public:
    void handle(DummyClassPtrType Dummy);
};

class ManagerClass
{
public:
    typedef boost::function<void (DummyClassPtrType Dummy)> HandlerFunctionType;
    typedef std::vector<HandlerFunctionType> HandlerFunctionListType;
    //
    HandlerFunctionListType HandlerFunctionList;
    void registerHandler(HandlerFunctionType Handler)
    {
        HandlerFunctionList.push_back(Handler);
    }
    void unRegister(HandlerFunctionType Handler)
    {
        // find the function pointer in the list and delete it from the list if found
        HandlerFunctionListType::iterator HandlerIter = HandlerFunctionList.begin();
        while (HandlerIter != HandlerFunctionList.end())
        {
            if (*HandlerIter == Handler) // error C2666: 'boost::operator ==' : 4 overloads have similar conversions
            {
                HandlerIter = HandlerFunctionList.erase(HandlerIter);
                break;
            }
            else
            {
                ++HandlerIter;
            }
        }
    }
};

int main()
{
    ManagerClass Manager;
    UpdaterClass Updater;
    Manager.registerHandler(boost::bind(&UpdaterClass::handle, &Updater, _1));
    Manager.unRegister(boost::bind(&UpdaterClass::handle, &Updater, _1));
    return 0;
}

编译器 (VS2008 SP1) 不喜欢这一行:

if (*HandlerIter == Handler)

我不知道如何实现这一目标。

最佳答案

除了 Yakk 的回答之外,另一种通常的实现方式是在容器中保留一个指向项目的迭代器(这个迭代器作用于 Yakk 所说的“ token ”)。

由于您可能会在删除特定项目之前删除和添加其他项目,因此您必须选择一个不会在插入/删除时使其迭代器失效的容器。 std::vector 显然不适合这个,但是 std::list 是。

您的 registerHandler 函数只需要返回 std::list::insert 返回的迭代器,而 unregisterHandler 只是一个调用 HandlerFunctionList.erase(iteratorToken); 的问题。

这个实现的唯一缺点是,与 Yakk 的不同,它不使用字典来存储 token ,因此它无法事先检查 token 的有效性,如果用户传递无效的迭代器,事情就会出错到您的 unregisterHandler

但是,好处是 boost 了性能,因为它完全避免了中间字典。

选择你的毒药。

关于c++ - 比较存储为 boost::function 的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717899/

相关文章:

c++ - 上传我的代码的最简单方法?

c++ - 使用异步函数提升 asio 编译错误

C++ 模板参数推导不起作用

c++ - 使用 C 和 C++ 的 Protocol Buffer

c++ - 使用 SFML 和 C++ 将像素打印到屏幕上

c++ - 许多 Boost::histogram 对象的动态分配

c++ - 删除 boost::bind 的原始指针参数

c++ - 字符串排序队列

c++ - 返回指向 protected 内部类元素的指针

c++ - boost::spirit::qi::lexeme 没有捕获完整的 token