首先感谢Noah Roberts的回答值得作为给予好评的是灵感,这个答案。
从他的回答中,我提取并重构了boost::mpl::for_each
和boost::mpl::range
,以获得我认为满足问题标准的最小完整定义。它不再对任何升压和扶养被用作这样的:
struct eat_fruit; // As Noah's answer
void eatAllFruit()
{
EnumIteration< Fruits, eApple, eTotal >::for_each(eat_fruit());
}
我EnumIteration
结构如下所定义的,我欢迎任何意见或改进。与Boost版本唯一的区别在于该范围不包括最终的枚举值(即eTotal
),而不包括包含它的boost::mpl::range
。
template< typename ENUM, ENUM BEGIN, ENUM END >
struct EnumIteration
{
private:
template< ENUM N >
struct Iterator
{
static const ENUM value = N;
typedef Iterator< static_cast<ENUM>(N+1) > next;
operator ENUM() const { return static_cast<ENUM>(this->value); }
};
template< typename T >
struct End
{ enum { value = false }; };
template<>
struct End< Iterator<END> >
{ enum { value = true }; };
template< bool done = true >
struct for_each_impl
{
template< typename Iterator, typename F >
static void execute(Iterator*, F) {}
};
template<>
struct for_each_impl<false>
{
template< typename Iterator, typename F >
static void execute(Iterator*, F f)
{
f(typename Iterator());
typedef typename Iterator::next next;
for_each_impl< End<next>::value >::execute(static_cast< next * >(0), f);
}
};
public:
template< typename F >
static void for_each(F f)
{
typedef Iterator<BEGIN> first;
for_each_impl< End<first>::value >::execute(static_cast< first * >(0), f);
}
};
这并不完全清楚你想要做什么,但它听起来像你想要使用虚拟功能。 – 2010-10-27 15:55:13
@Adam Rosenfield:我真的只是对这种模式感兴趣,这个问题来自http://stackoverflow.com/questions/3997038/ – dukedave 2010-10-27 16:04:32