C ++宏/元程序在编译时确定成员数 [英] C++ macro/metaprogram to determine number of members at compile time

查看:78
本文介绍了C ++宏/元程序在编译时确定成员数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有基于消息/类似异步代理的体系结构的应用程序. 将有几十种不同的消息类型,每种类型均由C ++类型表示.

I am working on an application with a message based / asynchronous agent-like architecture. There will be a few dozen distinct message types, each represented by C++ types.

class message_a
{
  long long identifier;
  double some_value;
  class something_else;
  ...//many more data members
}

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

Is it possible to write a macro/meta-program that would allow calculating the number of data members within the class at compile time?

//例如:

class message_b
{
  long long identifier;
  char foobar;
}


bitset<message_b::count_members> thebits;

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

I am not familiar with C++ meta programming, but could boost::mpl::vector allow me to accomplish this type of calculation?

推荐答案

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

No, there is no way in C++ to know the names of all members or how many members are actually there.

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

You could store all types in a mpl::vector along in your classes but then you face the problem of how to turn them into members with appropriate names (which you cannot achieve without some macro hackery).

使用std::tuple代替POD是一种通常可以使用的解决方案,但是当您实际使用元组(无命名变量)时会产生令人难以置信的混乱代码,除非您在某个时候对其进行了转换或具有将访问器转发至元组成员.

Using std::tuple instead of PODs is a solution that generally works but makes for incredible messy code when you actually work with the tuple (no named variables) unless you convert it at some point or have a wrapper that forwards accessors onto the tuple member.

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

带有Boost.PP和MPL的解决方案:

A solution with Boost.PP and 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;
}

我没有对其进行测试,因此可能存在错误.

I didn't test it so there could be bugs.

这篇关于C ++宏/元程序在编译时确定成员数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆