Using boost :: mpl :: lambda to remove types from boost :: mpl :: list based on static const member variable

I have a list of types defined as:

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

I would like to create a second list that does not contain any fruits, i.e. the resulting list formed from the first list will contain one type brick. Fruits are identified through a static constant variable defined inside types, for example:

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

I currently have a solution that includes creating a meta function class and using it boost::mpl::remove_if. I believe that I should make it more elegant using boost :: mpl :: lambda to remove the need for a separate structure RemoveFruit. Any suggestions on how to do this?

Full code as it stands now:

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;
}
+3
1

, , , 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;
+3

Source: https://habr.com/ru/post/1752165/


All Articles