#ifndef RSPSLINK_HPP
#define RSPSLINK_HPP
#include <assert.h>
#include <iostream>
#include <list>
#include <iterator>
#include <functional>
namespace whells
{
namespace dm {
template<typename itfcType>
class rsplink
{
public:
using interface_type = itfcType;
struct stLinkItem{
mutable interface_type * p_itfc;
interface_type* operator->(){
return p_itfc;
}
stLinkItem():p_itfc(nullptr){}
stLinkItem( interface_type * itfc ):p_itfc( itfc ){}
stLinkItem( const stLinkItem& b ):p_itfc( b.p_itfc ){}
stLinkItem( stLinkItem&& b ):p_itfc( b.p_itfc ){}
stLinkItem& operator=( stLinkItem&& b ){
p_itfc = b.p_itfc;
return *this;
}
};
using link_t = std::list<stLinkItem>;
using iterator = typename std::list<stLinkItem>::iterator;
protected:
link_t __m_link;
mutable iterator __m_curr_it;
bool __m_started;
public:
rsplink():__m_started( false ){}
virtual ~rsplink(){}
bool forward(std::function< void (stLinkItem& curr)> cb)
{
bool ret = true;
if(__m_link.size() == 0) return false;
if( __m_curr_it == __m_link.end() ){
__m_curr_it = __m_link.begin();
return false;
}
if( !cb ) return false;
if( __m_started == false ){
__m_started = true;
__m_curr_it = __m_link.begin();
}
cb( *__m_curr_it );
__m_curr_it ++;
return ret;
}
bool backward( std::function< void ( stLinkItem &curr ) > cb ){
bool ret = true;
if( __m_link.size() == 0 ) return false;
if( __m_curr_it == __m_link.rend() ){
__m_curr_it = __m_link.rend();
__m_curr_it ++;
return false;
}
if( __m_started == false ){
__m_started = true;
__m_curr_it = __m_link.rbegin();
}
if( !cb ) return false;
cb( *__m_curr_it );
__m_curr_it ++;
return ret;
}
iterator insert( iterator it , interface_type * rsps ){
assert( rsps );
stLinkItem item( rsps );
iterator ret = __m_link.insert( it , item ) ;
return ret;
}
/**
* @brief 添加处理接口
* @param 处理接口对象指针
*/
void push_back( interface_type * rsps ){
assert( rsps );
stLinkItem item( rsps );
__m_link.push_back( item );
}
/**
* @brief 移除尾部对象
*/
stLinkItem&& pop_back(){
stLinkItem item = __m_link.back();
__m_link.pop_back();
return std::move( item );
}
void erase( iterator it ){
__m_link.erase( it );
}
void clear(){
__m_link.erase( __m_link.begin() , __m_link.end() );
}
bool setFromFront(){
if( __m_link.size() == 0 ) return false;
__m_curr_it = __m_link.begin();
return true;
}
bool setFromEnd(){
if( __m_link.size() == 0 ) return false;
__m_curr_it = __m_link.end();
return true;
}
iterator begin(){ return __m_link.begin(); }
iterator end(){ return __m_link.end(); }
};
}
}
#endif // RSPSLINK_HPP
测试代码:
rsps1 a;
rsps2 b;
rsps.push_back( &a );
rsps.push_back( &b );
rsps.forward( [=]( rsplink<responseItfc>::stLinkItem& item ){
item->response( 10 );
} );
rsps.forward( []( rsplink<responseItfc>::stLinkItem& item ){
item->response( 10 );
} );
return 0;