#include template< bool C_ > struct bool_ { enum { value = C_ }; operator bool() const { return this->value; } }; typedef bool_ true_; typedef bool_ false_; //-------------------- struct auto_any_base { operator bool() const { return false; } }; template struct auto_any : auto_any_base { explicit auto_any(T const &t) : item(t) { } mutable T item; }; typedef auto_any_base const &auto_any_t; template inline T &auto_any_cast1(auto_any_t a) { return static_cast const &>(a).item; } namespace boka { namespace range_detail { template< typename T, std::size_t sz > inline T* range_begin1( T (&a)[sz] ) { return a; } template< typename T, std::size_t sz > inline T* range_end1( T (&a)[sz] ) { return a + sz; } } template< typename C > struct iterator1 { typedef typename C::iterator type; }; template< typename T, std::size_t sz > struct iterator1< T[sz] > { typedef T* type; }; template< class T > inline typename iterator1::type begin1( T& r ) { return range_detail::range_begin1( r ); } template< class T > inline typename iterator1::type end1( T& r ) { return range_detail::range_end1( r ); } namespace foreach_detail_ { template inline auto_any::type> begin11(T &t) { typename iterator1::type y = begin1(t); return auto_any::type>(y); } template inline auto_any::type> end11(T &t) { typename iterator1::type y = end1(t); return auto_any::type>(y); } template inline bool done1(auto_any_t cur, auto_any_t end, T&) { return auto_any_cast1(cur) == auto_any_cast1(end); } template struct reference2 { typedef typename T::reference type; }; template< typename T, std::size_t sz > struct reference2< T[sz] > { typedef T type; }; template inline typename reference2::type deref1(auto_any_t cur, T&) { return *auto_any_cast1::type>(cur); } template inline void next1(auto_any_t cur, T&) { ++auto_any_cast1::type>(cur); } }} inline bool set_false(bool &b) { b = false; return false; } #define BAIL boka::foreach_detail_ #define FOR_EACH(VAR, COL) \ if (auto_any_t _cur = BAIL::begin11( COL )){} else \ if (auto_any_t _end = BAIL::end11( COL )) {} else \ for (bool _conti = true; \ _conti && !BAIL::done1( _cur, _end, COL); \ _conti ? BAIL::next1( _cur, COL) : (void)0) \ if (set_false(_conti)){} else \ for (VAR = BAIL::deref1(_cur, COL); !_conti; _conti = true) void test() { int tbl[] = {1,2,3,4,5,6,7}; FOR_EACH( int i, tbl ) { std::cout << i << ' '; } } /* 第三章 尝试支持数组之二 为了解决上一章提到的两个问题,增加一个set_false函数 inline bool set_false(bool &b) { b = false; return false; } 使用了一个技巧: if (int i = 0) {} else 见附件 3.cpp 至此已经完全支持数组了: void test() { int tbl[] = {1,2,3,4,5,6,7}; FOR_EACH( int i, tbl ) { std::cout << i << ' '; } } 且支持 break, continue, 前if */