3

次のように定義されたタイプのリストがあります。

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

果物を含まない 2 番目のリストを作成したいと思います。つまり、最初のリストから形成された結果のリストには、単一タイプの Brick が含まれます。果物は、型内で定義された static 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 に答える