如何使用BOOST信号(二)

Slots aren't expected to exist indefinately after they are connected. Often slots are only used to receive a few events and are then disconnected, and the programmer needs control to decide when a slot should no longer be connected.

    Signal/slot disconnections occur when any of these conditions occur:

    -The connection is explicitly disconnected via the connection's            disconnect method directly, or indirectly via the signal's             disconnect method or scoped_connection's destructor.  

    -A trackable object bound   to the slot is destroyed.

    -The signal is destroyed.

 

 

Seg 1: Disconnecting slots.

        boost::signals::connection c = sig.connect(HelloWorld());

        if (c.connected()) {

        // c is still connected to the signal

        sig(); // Prints "Hello, World!"

        }

        c.disconnect(); // Disconnect the HelloWorld object

        assert(!c.connected()); //c isn't connected any more

        sig(); // Does nothing: there are no connected slots

Seg 2:

        boost::signals::connection c = sig.connect(HelloWorld());

        sig(); // Prints "Hello, World!"

 

        c.block(); // block the slot

        assert(c.blocked());

        sig(); // No output: the slot is blocked

 

        c.unblock(); // unblock the slot

        sig(); // Prints "Hello, World!"

Slots in the Boost.Signals library are created from arbitrary function objects, and therefore have no fixed type. However, it is commonplace to require that slots be passed through interfaces that cannot be templates. Slots can be passed via the slot_type for each particular signal type and any function object compatible with the signature of the signal can be passed to a slot_type parameter.

Seg 3:

class Button 

{

  

typedef boost::signal<void (int x, int y)> OnClick;

 

public:

  

void doOnClick(const OnClick::slot_type& slot);

 

private:

  

OnClick onClick;

};

 

void Button::doOnClick(

      

const OnClick::slot_type& slot

    

)

{

  

onClick.connect





(slot);

}

 

void printCoordinates(long x, long y)

{

  

std::cout << "(" << x << ", " << y << ")/n";

}

 

void f(Button& button)

{

  

button.doOnClick(&printCoordinates);

}

 

The doOnClick

 method is now functionally equivalent to the connect

 
method of the onClick signal, but the details of the doOnClick method
 can be hidden in an implementation detail file.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值