HN user

dctwin

77 karma
Posts2
Comments16
View on HN

Oh I think I finally groked what you suggested! Something like

template <StringLiteral str> static constexpr Key<str> key

in the class namespace - I think this this would work, but if I understand this correctly, You would need to do like

User user {...}; user[User::key<"myKey">]

Which actually is not so bad...

Whether or not this is useful (I am also not sure), the JSON doesn't need to survive into runtime at all. If you include the JSON, do a bunch of `if constexpr`, and never touch the JSON outside of a constexpr context, it doesn't have to any footprint on your binary. (I'm not sure if #embed will force stuff to stay in your binary even if you never reference it at runtime)

Yes, very true. I noticed that even already at 3dp the floats start to compare unequal. The long double helped but it's not really.

I googled and found two examples of constexpr float parsing repositories, but from the sounds of things, you understand this problem better than I and will have seen them already

You're right to point out that this is really 'first class JSON', rather than the Pydantic/Jackson type thing where the json barely exists and is immediately transformed into your models and classes.

Thanks for reading the article though, that's cool. I am a daw_json_link fan

The opposite 'toString' problem seems harder - I didn't try, but it should be possible now that std::string is constexpr.

I don't think you could parse it with, say, a class that has a std::string member (because of the transience restriction), but perhaps you can use lambdas that capture that string by reference, and call each other as appropriate?

As for exporting that as some sort of compiler artefact for use elsewhere, I am not sure how you would do that...

I was able to do the primitive

long double result = 0.0;

while (...) {

  if (json[head] == '.') ...

  result *= 10; result += json[head] - '0';
}

in a constexpr function with no problem :)

Hello! I wrote this short blog post about using pattern-matching-like template metaprogramming to deserialize JSON at build time - please let me know what you think (especially if you see improvements)