c++ - 一次性使用 Boost.MPL 定义标签和序列

标签 c++ boost c++03 boost-mpl

我对 Boost.MPL 有疑问,我不确定如何处理它。目前我的代码 看起来像这样:

struct Definition {
  typedef boost::mpl::int_<5> A;
  typedef boost::mpl::int_<3> B;
  typedef boost::mpl::int_<6> C;
  typedef boost::mpl::int_<1> D;
  // (...)

  typedef boost::mpl::vector<
    A
   ,B
   ,C
   ,D
    // (...)
  > Seq;
};

在这里,数字 Nmpl::int_< N >表示一些任意小数 数字。然后一些其他代码计算这些数字的总和 由“键”定义的类型,例如对于 Definition::D , 总和为 5 + 3 + 6 (A + B + C)。这需要在编译时完成。这就是为什么我使用 mpl::vector以及一些适当的元编程。

我不喜欢当前的方法,因为它在某种程度上违反了 DRY 规则。

我想知道是否可以提供这样的结构 定义而不需要在 mpl::vector 中重复类型名称为了 Seq类型。换句话说,我可能需要一堆宏 将允许我编写这样的代码:

struct Definition {
  FIELD(A, 5);
  FIELD(B, 3);
  FIELD(C, 6);
  FIELD(D, 1);
  // (...)
  GEN_SEQ() // only if really needed
};

然后 Definition::A仍会引用 boost::mpl::int_<5> , 或者 至少会允许我访问 boost::mpl::int_<5>不知何故,和 Definition::Seq会给我适当的 MPL 序列。

当然这只是我的想象。代码可能看起来不同,我是 只是在寻找选择。

最佳答案

你见过metamonad吗? ?它具有您想要的可变抽象:

#include <mpllibs/metamonad/eval_multi_let_c.hpp>
#include <mpllibs/metamonad/pair.hpp>
#include <mpllibs/metamonad/syntax.hpp>

#include <boost/mpl/plus.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/assert.hpp>

#include <mpllibs/metamonad/metafunction.hpp>
#include <mpllibs/metamonad/lazy_metafunction.hpp>
#include <mpllibs/metamonad/returns.hpp>
#include <mpllibs/metamonad/name.hpp>

#include <boost/mpl/int.hpp>
#include <boost/mpl/times.hpp>
#include <boost/mpl/divides.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/minus.hpp>
#include <boost/mpl/equal_to.hpp>

int main()
{
    using namespace mpllibs::metamonad::name;
    using boost::mpl::equal_to;
    using boost::mpl::plus;
    using boost::mpl::map;
    using boost::mpl::int_;

    using mpllibs::metamonad::eval_multi_let_c;
    using mpllibs::metamonad::syntax;
    using mpllibs::metamonad::pair;

    // test_evaluation_of_expression
    static_assert(
      equal_to<
        int_<14>,
        eval_multi_let_c<
          map<
              pair<a, syntax<int_<5>> >,
              pair<b, syntax<int_<3>> >,
              pair<c, syntax<int_<6>> >
          >,
          plus<a, b, c> >::type
      >::value, "Yay, maths still work"
    );
}

关于c++ - 一次性使用 Boost.MPL 定义标签和序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26473082/

相关文章:

c++ - 获取内联定义的友元函数的地址

c++ - C++ 中的动态结构

c++ - 如何在不与标准库运算符冲突的情况下为一组相关类模板重载运算符?

c++ - 如何在我的模板类中初始化这个静态类变量?

c++ - C++ 中的 int 和 double 运算

c++ - 尝试在 C++ 代码中包含 iPhone OpenGLES header

c++ - 访问boost线程对象的成员变量

python - 用 Python 构建 caffe(找不到 -lboost_python3)

c++ - 使用 boost program_options 进行动态配置

c++ - 如何在 C++03 中使用 "dereference a type"?