2010-08-06 73 views
1

升压信号允许通过连接成员功能暂时阻止连接。但是,我有一个单一的信号与许多连接。连接由各自的听众存储和维护。现在广播公司决定暂时停止发送信号。似乎没有办法迭代信号的所有连接或临时禁用整个信号。这对我来说似乎很奇怪,因为这种机制肯定必须存在于内部,以便信号在发出信号时到达所有用户......
我是否错过了什么?我怎样才能暂时禁用信号?阻止连接到升压信号的所有连接

回答

2

我不知道有什么办法直接做到这一点。如果您愿意永久断开所有插槽,则可以使用disconnect_all_slots()方法。例如:

boost::signal<int()> foo; 
... 
foo.disconnect_all_slots(); 

如果需要暂时阻止他们,我能拿出最好的解决办法是使用模仿这种行为的自定义组合。

#include <boost/signals.hpp> 
#include <iostream> 

//Define a reusable combiner that allows all slots to be blocked 
template <typename Combiner> 
struct blockable { 
    typedef typename Combiner::result_type result_type; 

    blockable() : blocked(false), combiner() {} 

    //Block or unblock all slots 
    void block() {blocked = true;} 
    void unblock() {blocked = false;} 

    template <typename InputIterator> 
    result_type operator()(InputIterator first, InputIterator last) { 
     //Either call into inner combiner, or throw if all slots are blocked 
     if (!blocked) return combiner(first, last); 
     throw std::runtime_error("All slots are blocked"); 
    } 
private: 
    bool blocked; 
    Combiner combiner; 
}; 

//Quick and dirty sample using the blockable combiner 
int bar() { 
    return 1; 
} 

int main() { 
    boost::signal<int(), blockable<boost::last_value<int> > > foo; 
    foo.connect(&bar); 
    try { 
     //show that it works 
     int x = foo(); 
     std::cout << x << std::endl; 
     //Now block all slots 
     foo.combiner().block(); 
     int y = foo(); 
     //This won't run since the last call to foo() should throw 
     std::cout << y << std::endl; 
    } catch (std::exception& e) { 
     //Should get here via 2nd call to foo() 
     std::cout << e.what() << std::endl; 
    } 
    return 0; 
}