简体   繁体   English

使用Boost C ++重新绑定类成员函数

[英]Rebinding class member function with boost c++

The example belows shows a class member binding with boost bind. 下面的示例显示了带有boost绑定的类成员绑定。 This works good but what if i want to rebind f to another class rebind2. 这很好,但是如果我想将f重新绑定到另一个类rebind2呢? I did not found any solution and calling bind with boost function didn't work. 我没有找到任何解决方案,并且使用boost函数调用bind无效。 Any idea how rebinding a class member function could work. 任何想法都可以重新绑定类成员函数。

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();
}

How about creating an intermediate binding? 如何创建中间绑定? I'm using the standard library here, but I'm sure you can substitute a Boost solution if you have to: 我在这里使用标准库,但是如果您必须执行以下操作,我可以确定可以替代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);

I'm not sure if this really solves any problem. 我不确定这是否真的可以解决任何问题。 You can always just write the complete bind expression again: 您总是可以再次编写完整的绑定表达式:

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

But maybe if your real use case has a lot of common, bound arguments, or bound arguments that you only want to evaluate once, then an intermediate binding may be useful. 但是,如果您的实际用例有很多公共的,绑定的参数,或者只想评估一次的绑定参数,那么中间绑定可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM