3 ms·
string_constant<'H', 'e', 'l', 'l', 'o'> Sometimes I see C++ code, and I feel deeply sad for the people that are subjected to it.
by James_K 3y ago
string_constant<'H', 'e', 'l', 'l', 'o'>
Sometimes I see C++ code, and I feel deeply sad for the people that are subjected to it.
- cristeigabriel 3y agoYou don't have to do this, here's an alternative approach: template<std::size_t N> struct fstr: public std::array<char, N + 1> { using std::array<char, N + 1>::array; constexpr fstr(const char* str) noexcept : std::array<char, N + 1>() { for (size_t i = 0; i < N; i++) (*this)[i] = str[i]; } }; template<std::size_t N> fstr(const char (&)[N]) noexcept -> fstr<N - 1>; template <fstr sz> struct log { log() { std::cout << std::string_view{ sz.data(), sz.size() } << std::endl; } }; int main() { log<"Hello, world!"> _; }
- eklitzke 3y agoThey're not actually writing these template instantiations, you would write regular strings in your code. The whole point is that this is for a logging library that does compile-time trickery to replace strings with integer labels. They have some compile-time tricks to convert the strings passed in logging macros to these template instantiations. I'm guessing the way it works is that since each of these template instantiations represents a unique type they can convert each type to a known numeric code, and then have a map of codes to the original strings to read the log data. But the point is you'd only have to deal with these weird templates if you're actually implementing or debugging the library, which hopefully you'd only have to do rarely (ideally just once!).
- pjmlp 3y agoThat is code from people not used to modern C++, as you can see from most replies here.