logoalt Hacker News

bluGillyesterday at 1:11 PM4 repliesview on HN

C++ conference speakers (including keynotes) are now begging everyone to stop using enum to string in their example. While they are a simple and easy to understand example, reflection is for much more interesting problems. I can't think of any other example that I would type into a comment box or put on a slide.


Replies

maccardyesterday at 2:08 PM

Serialization is the canonical example. Being able to turn

    struct MyStruct {
      int val = 42;
      string name = "my name";
    };
    
into

    {
      "val": 42, // if JSON had integers, and comments of course
      "name": "my name",
    }
is incredibly powerfuly. If reflection supported attributes (i can't believe it shipped without, honestly), then you could also mark members as [[ignore]] and skip them.
show 2 replies
cogman10yesterday at 2:02 PM

It comes up pretty frequently in java. Serialization/Deserialization, adding capabilities based on type, Adding new capabilities to a type, general tuning (for example, adding a timing or logging call onto methods).

Almost all the Java web frameworks are giant balls of reflection. Name a function the right way or add the right magic annotation and the framework will autowire it correctly.

It's a pretty powerful tool. (IDK if C++'s reflection is as capable, but this is what was enabled by java's reflection).

show 2 replies
theICEBeardkyesterday at 6:51 PM

I mean a readable implementation of tuple with minimal overhead is a great case for me (went from around 1.6k lines to approximately 250 lines). I wrote an implementation including the normally difficult to implement tuple_cat based on c++26 within a few hours.

My favorite thing is that I will get to remove and replace most of the cryptic template recursion stuff I have with "template for" and maybe a bit of reflection. Debugging the unrolled stuff will be a joy in comparison.

surajrmalyesterday at 1:16 PM

Anybody the derive traits rust has are a good demo.