PrevUpHomeNext

Visitable Structures

The visit_struct library is a miniature reflection library.

It provides some macros that allow you to define an arbitrary C++ struct as a "visitable structure". This means that you can apply any generic function object to the pairs formed of its field names and values in sequential order.

Usually, you will declare all the members as "visitable" when you do this, but you don't have to.

See visit_struct docs for more info.

In Primer

This library is integrated with Primer:

Primer has a specialization of push and read for any visitable structure, which you can get via

#include <primer/visit_struct.hpp>

Basically, the struct definition becomes a schema for a table layout.

When a visitable structure is pushed:

When a visitable structure is read:

Example

The use of this can be seen with an example.

Here we are demonstrating a form of "named parameters" in a callback function. The argument to a function is expected to be a single lua table. A visitable structure is used so that the arguments are automatically parsed into a struct. Note that we are using boost::optional as some of the structure members, so that those entries don't have to appear in the table.

lua:

h{ name = 'Charlie', id = 44 }

C++:

struct h_arguments {
  std::string name;
  int id;
  boost::optional<int> group;
  boost::optional<std::string> task;
};

VISITABLE_STRUCT(h_arguments, name, id, group, task);

primer::result h(lua_State * L, h_arguments args) {
  auto it = database.find(args.id);
  ...
}
Hana and Fusion

Note that, because visit_struct has compatibility headers for boost::hana and boost::fusion, any "fusion adapted structure" or hana::struct may be read or pushed in this manner as well.


PrevUpHomeNext