Compile-time reflection in C++1z?

Vincent picture Vincent · Mar 5, 2014 · Viewed 8.9k times · Source

There is a study group in the C++ standardization committee to provide compile-time reflection in C++1z or after. I would like to know what is exactly the purpose and how powerful the expected tools will be?

For example will it be possible to name functions or classes using these tools?

struct A {int f() {return 42;}};
struct B {int (std::reflect<A>::member<0>::declname)() {return 43;}};
// equivalent to struct B {int f() {return 43;}};

If it would not be as powerful as this, what the typical use cases will be?

Answer

Andrew Tomazos picture Andrew Tomazos · Mar 5, 2014

Reflection use cases are outlined in N3814:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3814.html

The general view is that we will do it as an extension of the Type Traits library as exemplified by N3815:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3815.html

There are two parts to reflection. The first is introspection. Taking an entity and querying constant values about it. The second is reification, which is the opposite - using values to create new entities.

For introspection - you can expect additional traits that will allow you to enumerate and get the names of class members, base classes, enumerators, function paramaters and so forth at compile-time. From there you can use them for things like serialization, memberwise operations, static checks and various other things.

Additionally later we are looking at reification, which would involve creating new entities from constant values with more expressiveness than you can with a template. So perhaps you might fill out a std::class_specifier s struct and then call make_type_from_spec(s) to create the type.

The introspection approach has more consensus at the moment, the reification side is further off.