c++ - 使用 boost::mpl::lambda 从基于静态常量成员变量的 boost::mpl::list 中删除类型

标签 c++ lambda boost-mpl

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

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

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

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;
}

最佳答案

我认为你能做的最好的事情就是像这样定义一个 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 字段。

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

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

关于c++ - 使用 boost::mpl::lambda 从基于静态常量成员变量的 boost::mpl::list 中删除类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3136790/

相关文章:

c++ - 将 boost::mpl::list 应用于类型的模板参数

c++ - boost mpl 字符串

c++ - boost::mpi 在具有相同标签的多个 isend/irecv 传输中抛出 MPI_ERR_TRUNCATE

c++ - 命名空间与两个大型库发生冲突

c++ - MFC面板和窗口句柄

c# - Expression<Func<T,bool>> 声明是什么意思?

ruby - 对如何在 ruby​​ 中使用 lambda 进行选择感到困惑

c++ - 所有线程都做同样的事情。程序文件

c++ - 如何隐藏显示 HTML5 标记的 Web 浏览器控件 (IE) 的滚动条和窗口边框?

c# - 如何在 C# 中转换表达式树 lambda?