使用提升 c++ 重新绑定类成员函数

Rebinding class member function with boost c++

本文关键字:绑定 函数 成员 新绑定 c++      更新时间:2023-10-16

下面的示例显示了带有 boost 绑定的类成员绑定。这很好用,但是如果我想将 f 重新绑定到另一个类 rebind2 怎么办。我没有找到任何解决方案,并且使用boost函数调用绑定不起作用。任何知道重新绑定类成员函数如何工作。

class RebindTest {
public:
    std::string name;
    RebindTest(std::string n){
        name = n;
    }
    void print(){
        std::cout << name << std::endl;
    }
};
int main(int argc, char **argv){
    RebindTest rebind1("rebind1");
    RebindTest rebind2("rebind2");
    typedef void (RebindTest::*fPtr)(void);
    boost::function<void(void)> f;
    f = boost::bind(&RebindTest::print,rebind1);
    f();
}

如何创建中间绑定?我在这里使用标准库,但我相信如果您必须,您可以替换 Boost 解决方案:

auto BoundPrint = std::mem_fn(&RebindTest::print);
// can use: BoundPrint(rebind1), BoundPrint(rebind2), etc.
std::function<void()> f = std::bind(BoundPrint, rebind1);
// assign new binding
f = std::bind(BoundPrint, rebind2);

我不确定这是否真的解决了任何问题。您始终可以再次编写完整的绑定表达式:

f = std::bind(&RebindTest::print, rebind2);

但是,如果您的实际用例有很多常见的绑定参数,或者您只想评估一次的绑定参数,那么中间绑定可能会很有用。