Hacker News new | ask | show | jobs
by CalChris 2650 days ago
This is similar to the C preprocessor trick STRINGIZE:

  #define STRINGIZE_DETAIL(x) #x
  #define STRINGIZE(x)        STRINGIZE_DETAIL(x)
2 comments

It probably uses stringification under the hood, but then relies on constexpr to "canonicalize" the name (removing everything before the dot, template parameters etc).
From cursory reading, it seems it doesn’t, at all. It uses compiler-specific predefined values __PRETTY_FUNCTION__ (gcc, clang) or __FUNCSIG__ (MS Visual C++), and doesn’t work on other compilers.

It also has to do work to extract the function name from the char arrays/C strings that those macros expand to.

Reading answers to https://stackoverflow.com/questions/4384765/whats-the-differ..., it seems it would have been easier to use the __FUNCTION__ in gcc, but I’m not familiar with that (or the other predefined values) at all, so who knows?

Actually, __FUNCTION__ won't work as it only expands to the name of the function, not any templates or arguments.

It's actually a pretty clever way to automagically deduce not only names of variables but also of enums :). Too bad it's most likely not maintainable in the long run as compilers probably change what their __PRETTY_FUNCTION__ (or equivalent) macros expand to in new versions.

I usually check the newest versions of compilers, and if the behavior changes, then I update the code
Last I knew __FUNCTION__ in GCC doesn't even do name de-mangling. You'd get the raw C symbol name with no C++ types.
Gcc 7. I could be wrong but I seem to recall a long time ago, when I was learning this stuff in the 90s, __FUNCTION__ wouldn't even demangle.
yeap, I use __PRETTY_FUNCTION__.
You are absolutely right :)
That was what I was thinking, then I saw that this will stringify enum values, eg. nameof(c) returns "RED", which the preprocessor #x will not do.
To be sure: nameof(c) returns "c" (nameof return name of variable) nameof_enum(c) returns "RED" (nameof_enum return enum name of enum variable)
I only use STRINGIZE for error messages. I learned about it from reading the source for assert macros.