C++ 宏/元程序在编译时确定成员数量

MW_*_*dev 6 c++ macros metaprogramming

我正在开发一个具有基于消息/异步代理类架构的应用程序。将有几十种不同的消息类型,每一种都由 C++ 类型表示。

class message_a
{
  long long identifier;
  double some_value;
  class something_else;
  ...//many more data members
}
Run Code Online (Sandbox Code Playgroud)

是否可以编写允许在编译时计算类中数据成员数量的宏/元程序?

//例如:

class message_b
{
  long long identifier;
  char foobar;
}


bitset<message_b::count_members> thebits;
Run Code Online (Sandbox Code Playgroud)

我不熟悉 C++ 元编程,但是 boost::mpl::vector 可以让我完成这种类型的计算吗?

pmr*_*pmr 3

不,C++ 中无法知道所有成员的名称或实际有多少个成员。

您可以将所有类型存储在mpl::vector您的类中,但是您面临的问题是如何将它们转换为具有适当名称的成员(如果没有一些宏黑客技术,您就无法实现这一点)。

使用std::tuplePOD 代替是一种通常有效的解决方案,但当您实际使用元组(无命名变量)时,会产生令人难以置信的混乱代码,除非您在某个时刻转换它或有一个将访问器转发到元组成员的包装器。

class message {
public:
  // ctors
  const int& foo() const { return std::get<0>(data); }
  // continue boiler plate with const overloads etc

  static std::size_t nun_members() { return std::tuple_size<data>::value; }
private:
  std::tuple<int, long long, foo> data;
};
Run Code Online (Sandbox Code Playgroud)

使用 Boost.PP 和 MPL 的解决方案:

#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/preprocessor.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>

struct Foo {
  typedef boost::mpl::vector<int, double, long long> types;

// corresponding type names here
#define SEQ (foo)(bar)(baz)
#define MACRO(r, data, i, elem) boost::mpl::at< types, boost::mpl::int_<i> >::type elem;
BOOST_PP_SEQ_FOR_EACH_I(MACRO, 0, SEQ)

};

int main() {
  Foo a;
  a.foo;
}
Run Code Online (Sandbox Code Playgroud)

我没有测试过,所以可能会有错误。