でも僅かばかり「foreach だけ使いたいのにライブラリを boost 依存にするのもなぁ…」と思ってしまったのが事の始まり。
なんやかんやで書いてしまいました。
車輪?大丈夫です。問題ありません。
//=============================================================================
// Foreach
//-----------------------------------------------------------------------------
///**
// @file Foreach.h
// @brief Foreach
// @author Riki
//*/
//=============================================================================
#pragma once
namespace Lumine
{
namespace Base
{
namespace Foreach
{
struct any_itr_base
{
operator bool() const { return true; }
};
template
struct any_itr
: any_itr_base
{
explicit any_itr( ITR_T const &t_ )
: Item( t_ )
{}
mutable ITR_T Item;
};
typedef any_itr_base const &any_itr_t;
template
struct col_type
{
typedef typename COL_T::iterator itr_type;
};
template
inline any_itr::itr_type > begin( COL_T& col_ )
{
return any_itr( col_.begin() );
}
template
inline any_itr::itr_type > end( COL_T& col_ )
{
return any_itr( col_.end() );
}
template
inline typename COL_T::iterator& get_itr( any_itr_t any_itr_, COL_T& )
{
return static_cast const& >( any_itr_ ).Item;
}
} // namespace Foreach
} // namespace Base
} // namespace Lumine
#define ln_foreach( var_, col_ ) \
if ( Lumine::Base::Foreach::any_itr_t _ln_foreach_cur_ = Lumine::Base::Foreach::begin( col_ ) ) \
if ( Lumine::Base::Foreach::any_itr_t _ln_foreach_end_ = Lumine::Base::Foreach::end( col_ ) ) \
for ( \
bool _ln_foreach_continue_ = true; \
Lumine::Base::Foreach::get_itr( _ln_foreach_cur_, col_ ) != Lumine::Base::Foreach::get_itr( _ln_foreach_end_, col_ ); \
++Lumine::Base::Foreach::get_itr( _ln_foreach_cur_, col_ ), _ln_foreach_continue_ = true ) \
for ( var_ = *Lumine::Base::Foreach::get_itr( _ln_foreach_cur_, col_ ); _ln_foreach_continue_; _ln_foreach_continue_ = false )
使い方はこんな感じ。
void main()
{
std::vector ary;
ary.push_back(2);
ary.push_back(5);
ary.push_back(7);
ary.push_back(8);
ln_foreach( int a, ary )
{
std::cout ::iterator itr = ary.begin();
std::vector::iterator end = ary.end();
for ( ; itr != end; ++itr )
{
int a = *itr;
std::cout << a << std::endl;
}
とりあえず vc++ と gcc でコンパイル確認しました。
パフォーマンスもboostと変わらないはず。
普通に使っていただくもよし、template の変態な使い方を参考にするもよし(本家はもっとすごいですけどね…)。
どこかの誰かの助けになりますように。なんて。