Static reflection for Protobuf in C++

46 views Asked by At

This is a bit of a "moon shot", but still: does the C++ Protobuf implementation support "static reflection"; or is there a way to make this work?

My goal is to have an API e.g. like this:

template<typename ProtobufMsg, typename MemberType, typename... PbMemberName>
MemberType& get_pb_mutable_ref(ProtobufMsg &msg, PbMemberName... path_elements);

So that I can call it e.g. like this:

auto &member_ref = get_pb_mutable_ref(my_pb_msg, "member_x", "sub_member_y");
member_ref = "abc";

The get_pb_mutable_ref() call would return a mutable reference, as if I had called my_pb_msg->mutable_member_x()->mutable_sub_member_y().

The type of member_ref should be deduced at compile time; and if the specified path_elements do not lead to a valid member, a compiler error should be raised.

Background: I want to use such an API to create helper functions through which members can be modified (with compile-time checking), so that the helper function can intercept and record the change.

1

There are 1 answers

1
MSalters On

That cannot work. C++ cannot deduce MemberType. Furthermore, PbMemberName would easily be deduced as a list of const char*, there's no need to have that as a template parameter

C++ Template Argument Deduction is based on the type of the function call expression, not the actual arguments. In this example, that signature would be (ProtobufMsg, const char*, const char*). This information does not include "member_x", "sub_member_y"

You would need something like &ProtobufMsg::member_x and ProtobufMsg::PartX::sub_member_y, which would be strongly typed pointers to members.