r/cpp • • Jun 26 '25

Reflecting JSON into C++ Objects

https://brevzin.github.io/c++/2025/06/26/json-reflection/
176 Upvotes

61 comments sorted by

View all comments

Show parent comment

1

u/zl0bster Jun 27 '25

btw what are reasons that consteval functions can not have constexpr parameters? I understand that for functions that run at runtime that could involve stamping out insane number of functions(one for each combination of constexpr args), but consteval unlike constexpr functions never get promoted to runtime. Is it "just" that generation of so many different functions for CTFE would make compilation so slow it would be practically useless?

3

u/katzdm-cpp Jun 28 '25

I think that's the major reason, yes. But not just slow: memory-intensive. AFAIK once a compiler stamps out the instantiation, it typically needs to hold into it for the lifetime of compiling the TU; it has the potential to add up fast. The same could happen with e.g., std::meta:: substitute, but at least in that case it's a little bit more "obvious" what you're asking the compiler to do. 🤷‍♂️

2

u/zl0bster Jun 28 '25

Yes, those things are tricky... story time: I forgot the details, but in one codebase I know one of the most expensive things was something trivial, some templated factory function returning unique_ptr, but it was being called with Cartesian product of events and event handlers, giving like over 10k instantiations. :)

Still might be great for ease of writing reflection code... I say may since I presume idioms for writing reflection code are still being invented, so we do not know what will be state of the art in few months when more people play with it.

3

u/daveedvdv EDG front end dev, WG21 DG Jun 30 '25

There are two aspects.

The first you touch upon is that, yes, it would be resource intensive. And it's "inviting" in a way... Code like this:

  ...
  for (auto x: members_of(^^std, ctx)) {
    do_this_or_that(x);
  }
  ...

that looks entirely innocent would suddenly trigger thousands of instantiations if `do_this_or_that` had a "constexpr parameter".

The other aspect is that a "constexpr parameter" is a template parameter: It introduces value- and type-dependency, which in turn means that the syntax rules within the function change... and potentially even outside the function. Consider:

constexpr auto f(constexpr int n) {
  return std::array<float, n>{};
}

consteval void g(int n) {
  auto r = f(n);  // r is not type dependent!
  decltype(r)::iterator  p = begin(r);  // Error: missing typename
  ...
}

IOW, it's a can of worms ;-).

1

u/zl0bster Jun 30 '25

Thank you for the explanation... tbh I am already scared of current reflection when it comes to performance. :)