温馨提示×

c++ delegate如何解绑

c++
小樊
83
2024-07-15 23:58:51
栏目: 编程语言

在C++中,通常使用函数指针来模拟委托的功能。要解绑委托,可以将函数指针设置为nullptr。下面是一个简单的示例代码:

#include <iostream>

class Delegate {
public:
    typedef void (*FunctionPtr)();

    void bind(FunctionPtr fn) {
        m_fn = fn;
    }

    void unbind() {
        m_fn = nullptr;
    }

    void invoke() {
        if (m_fn) {
            m_fn();
        } else {
            std::cout << "Delegate is not bound" << std::endl;
        }
    }

private:
    FunctionPtr m_fn;
};

void hello() {
    std::cout << "Hello, World!" << std::endl;
}

int main() {
    Delegate delegate;
    
    delegate.bind(&hello);
    delegate.invoke();
    
    delegate.unbind();
    delegate.invoke();
    
    return 0;
}

在这个示例中,Delegate类用函数指针实现了简单的委托功能。在main函数中,我们首先绑定了一个函数hello到delegate,并调用了invoke函数来执行hello函数。然后通过unbind函数解绑了hello函数,再次调用invoke函数则会输出"Delegate is not bound"。

通过这种方式,我们可以实现委托的绑定和解绑操作。需要注意的是,在实际开发中,可以使用更加复杂和强大的委托库,比如boost::function等。

0