ARTICLE AD BOX
A while ago I watched this talk by Herb Sutter, which showed some in my eyes nice ways to do class metaprogramming, e.g. to generate methods based on the members, like:
class MyClass(serializable, allocator_aware) { myStd::vector mMember; } auto alloc = myStd::alloc(); auto instance = MyClass(alloc); auto moved = MyClass(std::move(instance), alloc);Now when I read that C++26 has landed with reflections I thought I could write something like the above ... but crucially, while one can now do metaprogramming on members with nonstatic_data_members_of, add annotations to them and access members using .[:...:], I do not see how I can currently inject methods to a class or generate aggregate initializers. The closest I got with a quick draft for the allocator_aware (- that the class has a constructor with an allocator that it supplies to all its members, also for moving/copying) is a function similar to construct_at which generates some form of aggregate initialization (it compiles, at least):
#include <meta> struct Alloc {}; struct Member { Member() = delete; Member(Alloc&) {} }; struct Nested { Member m1; Member m2; }; template<typename T> T* construct(Alloc& alloc) { T* result = static_cast<T*>(static_cast<void*>(new char[sizeof(T)])); template for (constexpr auto member : define_static_array(std::meta::nonstatic_data_members_of(^^T))) { using MemberT = typename[:type_of(member):]; result->[:member:] = MemberT(alloc); } return result; } int main() { Alloc alloc; // prohibited: // auto nested = Nested {}; // manual // auto nested = Nested { .m1 = Member(alloc), .m2 = Member(alloc) }; // with reflection: auto nested = construct<Nested>(alloc); }But it is slightly ugly and not really nice to use. So, did I overlook something in the current C++26 standard, or are there upcoming proposals that would enable something like this? Without this, I feel reflection does not add that much value as apart from member reflection, one can already achieve much with templates already ...
