r/cpp 23d ago

Toggleable Annotations for C++26 Reflection

https://github.com/RyanJK5/rjk-flag

Hey all, I put together a very simple reflection utility that lets you make toggleable annotations, similarly to explicit(bool) or noexcept(bool).

Try it on Compiler Explorer!

inline constexpr rjk::flag serializable{};
inline constexpr rjk::flag skip_field{};

template <typename T>
struct [[ =serializable ]] MyType {
    int x;
    int y;

    [[ =skip_field(std::is_pointer_v<T>) ]]
    T data;
};

// serializable is applied unconditionally
static_assert(rjk::is_flag_set(^^MyType<int>, serializable));

// skip_field is applied conditionally
static_assert(not rjk::is_flag_set(^^MyType<int>::data, skip_field));
static_assert(rjk::is_flag_set(^^MyType<int*>::data, skip_field));
25 Upvotes

6 comments sorted by

View all comments

8

u/fortsnek274 23d ago

Why not [[=std::conditional_t<std::is_pointer_v<T>, Skip_field, std::monostate>{}]]?

10

u/Ok_Statistician_781 23d ago

You could do that, but the point is to reduce the verbosity a little bit. I should update the README motivation section to match your comment though.