简体   繁体   English

使用Boost Hana反映C风格的数组

[英]Reflecting C-style arrays with Boost Hana

BOOST_HANA_DEFINE_STRUCT is a fantastic macro when declaring structures with introspection. 在使用内省声明结构时, BOOST_HANA_DEFINE_STRUCT是一个很棒的宏。 If I have a structure like this: 如果我有这样的结构:

struct Person {
  std::string name;
  std::string last_name;
  int age;
};

We can add introspection by redefining it like this: 我们可以通过重新定义它来添加内省:

struct Person {
  BOOST_HANA_DEFINE_STRUCT(Person,
    (std::string, name),
    (std::string, last_name),
    (int, age)
  );
};

But what if we have a structure like this: 但是,如果我们有这样的结构怎么办:

struct Person {
  float eye_dioptre[2];
};

How would I use the BOOST_HANA_DEFINE_STRUCT syntax to reflect a C-style array? 我如何使用BOOST_HANA_DEFINE_STRUCT语法来反映C风格的数组? I've tried: 我试过了:

struct Person {
  BOOST_HANA_DEFINE_STRUCT(Person, 
    (float[2], eye_dioptre),   // error: expected unqualified-id before ‘[’ token
    (float, eye_dioptre[2])    // error: template argument 2 is invalid  BOOST_HANA_DEFINE_STRUCT(structure_name, __VA_ARGS__ );                    
  );
};

Both options above give compiler errors. 以上两个选项都会产生编译器错 The answer I'm expecting is "you should use c++-style arrays". 我期待的答案是“你应该使用c ++风格的数组”。 That could be done like so: 这可以这样做:

struct Person {
  BOOST_HANA_DEFINE_STRUCT(Person,
    (std::array<float,2>, eye_dioptre)
  );

But is there a way to do it with C-style arrays? 但有没有办法用C风格的数组做到这一点? }; };

The only way I can think of is either by just using a pointer, which I presume you don't want, or using a template alias , which would be something like: 我能想到的唯一方法是使用一个我认为你不想要的指针,或者使用模板别名 ,这可能是这样的:

template<size_t N>
using floatArr = float[N];

And when defining the struct : 在定义struct

struct Test {
    BOOST_HANA_DEFINE_STRUCT(Test,
        (floatArr<2>, example)
    );
};

An example program that illustrates this working: [GCC] 一个示例程序说明了这个工作: [GCC]

In fact, you could even generalize this alias for any type as well: 实际上,你甚至可以为任何类型推广这个别名:

template<typename T, size_t N>
using CArray = T[N];

Now a C Style Array of any type can be used with BOOST_HANA_DEFINE_STRUCT using a syntax such as CArray<float, 2> example . 现在,可以使用诸如CArray<float, 2> example类的语法将任何类型的C样式数组与BOOST_HANA_DEFINE_STRUCT使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM