从 std::function 获取对象上下文

Get object context from std::function

本文关键字:取对象 上下文 获取 function std      更新时间:2023-10-16

我有一个指向类成员函数的std::function,例如&Foo:barstd::function对象是否记录对象上下文,例如Foo*?有没有办法从std::function对象/类中获取上下文?

目的是找出我的函数unordered_multimap是否已经包含该上下文中的函数(但不一定是同一个类成员函数)。

例;

std::unordered_multimap<int, std::function<int(int)>> callbacks;
Foo* myFoo = new Foo();
callbacks[1].emplace( std::bind(&Foo::bar, myFoo, std::placeholders::_1) );
callbacks[1].emplace( std::bind(&Foo::bar2, myFoo, std::placeholders::_1) ); // now callbacks contains 2 functions for the same object/context. I want to avoid this
// Check context exists before inserting
auto vCallbacks = callbacks.equal_range(1);
for (auto iter = vCallbacks.first; iter != vCallbacks.second; iter++) {
    std::function<int(int)> func = iter->second;
    // somehow check function object for context myFoo
    if (func.??? == myFoo)
        // Sorry cant add callback because this object already has registered one
}

不,它没有。您基本上无法以任何有用的方式检查std::function的内容。