by kccqzy · 3y ago · 0 comments
You are pretty much limited to macros and macro-like languages (llvm-tablegen) if you want to do this today.
Users, library writers, and compiler writers all benefit from this in some way.
Also, constexpr symbols can be demoted to regular const as needed by the compiler if necessary, such as when getting a pointer to one. constexpr doesn't mean "compile-time only", it means "compile-time compatible"
If I recall correctly, from C++20 onward all member functions of std::string are constexpr.
That assumes your API accepts string views. How do you pass a string_view (safely) to fopen, or CreateFile (on windows)?
Then again, I am primarily a Python and C programmer, so there is likely some underlying reasoning I'm missing.
For const std::string&, you're further incurring a copy in order to create a temporary std::string.
So you might need to deal with a string that looks like "foo\0bar\0\0".
Putting together strings through string interpolation involving somewhat expensive operations is a common usecase. Given the choice, it's preferable to not have to compute them each and every single time a function is invoked.
If there was reflection, it would be useful to talk about class names, function names, etc, at compile time.
template<class E> requires std::is_enum_v<E> constexpr std::string_view joinedEnum() {
constexpr auto generate = [] -> std::string {
return []<template<class...> class L, class... D>(L<D...>) {
std::string str;
(((str += (str.empty() ? "" : ", ")) += D::name), ...);
return str;
}(boost::describe::describe_enumerators<E>());
};
static constexpr auto arr = [&] {
constexpr std::size_t N = generate().size();
std::array<char, N> arr;
std::char_traits<char>::copy(arr.data(), generate().data(), N);
return arr;
}();
return std::string_view(arr);
}
Note that you have to generate the constexpr std::string twice; once for its size, once for its contents. But you assume that the compiler can memoize the result.