3

我有一个类型列表定义为:

typedef boost::mpl::list<Apple, Pear, Brick> OriginalList;

我想创建一个不包含任何水果的第二个列表,即从第一个列表形成的结果列表将包含一个单一类型的 Brick。Fruit 通过定义在类型中的静态 const 变量来识别,例如:

struct Apple
{
    static const bool IsFruit = true;
};

我目前有一个解决方案,涉及创建一个元函数类,并使用boost::mpl::remove_if. 我相信我应该能够通过使用 boost::mpl::lambda 来消除对单独RemoveFruit结构的需求,从而使其更加优雅。关于如何做到这一点的任何建议?

目前的完整代码:

include <boost/static_assert.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/remove_if.hpp>
#include <boost/mpl/size.hpp>

#include <iostream>

struct Apple
{
  static const bool IsFruit = true;
};

struct Pear
{
  static const bool IsFruit = true;
};

struct Brick
{
  static const bool IsFruit = false;
};

typedef boost::mpl::list<Apple, Pear, Brick> OriginalList;
BOOST_STATIC_ASSERT(boost::mpl::size<OriginalList>::type::value == 3);

// This is what I would like to get rid of:
struct RemoveFruit
{
  template <typename T>
  struct apply
  {
    typedef boost::mpl::bool_<T::IsFruit> type;
  };
};

// Assuming I can embed some predicate directly in here?
typedef boost::mpl::remove_if<
  OriginalList,
  RemoveFruit
  >::type NoFruitList;

BOOST_STATIC_ASSERT(boost::mpl::size<NoFruitList>::type::value == 1);

int main()
{
  std::cout << "There are " << boost::mpl::size<OriginalList>::type::value << " items in the original list\n";
  std::cout << "There are " << boost::mpl::size<NoFruitList>::type::value << " items in the no fruit list\n";


  return 0;
}
4

1 回答 1

3

我认为您能做的最好的事情就是定义一个 IsFruit 结构,例如

template  <typename T> struct isFruit : boost::mpl::bool_<T::IsFruit> {};

然后你可以将你的无水果清单定义为

typedef boost::mpl::remove_if<
  OriginalList,
  boost::mpl::lambda< isFruit< boost::mpl::_1 > >::type
  >::type NoFruitList;

需要额外的结构来访问类中的 IsFruit 字段。

请注意,如果您想完全摆脱额外的结构,则必须重命名其他类的布尔成员。如果您遵循 boost::mpl 约定并调用它们value而不是IsFruit,则可以将 NoFruitList 定义为

typedef boost::mpl::remove_if<
      OriginalList,
      boost::mpl::lambda<boost::mpl::_1>::type
      >::type NoFruitList;
于 2010-06-29T00:24:52.240 回答