TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 230 subscribers
Post #25136 10
Strategies for requiring designated initializers when constructing a type?

Given some aggregate like this:

struct InitParams {
int size = 0;
int capacity = 0;
};

And given that it is used in some factory function like this:

auto Make(InitParams ip = {}) -> std::optional<MyClass>;

I want to design the aggregate type to allow callsites like...

Make({ .size = 10, .capacity = 20 });
Make({ .size = 10 });
Make({ .capacity = 20 });
Make({});
Make();

But I also want to reject callsites like...

Make({ 10, 20 });
Make({ 10 });
Make({ 20 }); // Oops! This is the size, not the capacity!

I was hoping that reflection would unlock the ability to specify this on the type alone somehow, but I've been unable to figure out how to do it.

I can approximate this behavior using an overload set where a similar-but-different param type is accepted by a different Make overload but then that would result in default construction being ambiguous too. You can see that in action here:

struct DesignatedInitRequired {
int DONOTSPELLTHISFIELDNAME0;
int DO
NOTSPELLTHISFIELDNAME1;
};

auto Make(DesignatedInitRequired dir = {}) -> void = delete("Use designated init");

Make({ 10 }); // Ambiguous, ill formed (which is what I want)
Make({ 10, 20 }); // Ambiguous, ill formed (which is what I want)
Make({}); // Ambiguous, ill formed (which is NOT what I want)
Make(); // Ambiguous, ill formed (which is NOT what I want)

So I could make something to reflect on InitParams and produce DesignatedInitRequired, but that wouldn't be enough. Every function that accepts InitParams would need an overload for DesignatedInitRequired meaning that it becomes a property of the type AND its users, not just the type itself.

Any ideas on how to achieve my goal?

https://redd.it/1t4l00s
@r_cpp
Reddit From the cpp community on Reddit Explore this post and more from the cpp community
More from @r_cpp
  1. Oct 3, 2026Teodorescu - [https://youtu.be/vVFFW6hoG1Y](https://youtu.be/vVFFW6hoG1Y) * Demystifying C…
  2. Oct 3, 2026New C++ Conference Videos Released This Month - September 2026 (Updated To Include Videos…
  3. Oct 3, 2026HPX 2.0.0 RC1 Released! – The HPX Project HPX is a general-purpose parallel C++ runtime sy…
  4. Oct 3, 2026[PLDI'26] Persistent Iterators with Value Semantics https://www.youtube.com/watch?v=cq33C5…
  5. Oct 3, 2026A Cross-Toolkit Timeline Control, Wed, Oct 14, 2026, 6:00 PM https://www.meetup.com/utah-c…
  6. Oct 3, 2026Upcoming C++ User Group meetings in October https://meetingcpp.com/meetingcpp/news/items/U…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →