Код: Выделить всё
template
static constexpr std::string GetAllEnumNamesAsString()
{
const std::string space = " ";
constexpr std::array names = magic_enum::enum_names();
std::string all{ names[0] };
for (int i = 1; i < names.size(); i++)
all += (space + std::string{ names[i] });
return all;
}
Код: Выделить всё
int main()
{
// must be allowed at compile time because it's part of a static_assert
static_assert(GetAllNames().length() == 17);
// but compiler makes this pure runtime - not even the final string is placed in static storage to copy to the heap
const std::string names = GetAllNames();
printf("%s\n", names.c_str());
return 0;
}
< /code>
Как лучше всего обойти это, чтобы использовать строковый буфер с составщиком компилятора? В моем ограниченном понимании Contexpr Код: Выделить всё
template
class FakeStringView
{
public:
constexpr FakeStringView(const std::string_view& s1) : _array{}
{
for (auto i = 0; i < s1.length(); ++i)
_array[i] = s1[i];
}
constexpr std::string_view Get() const
{
return { _array.data(), _array.size() };
}
private:
std::array _array;
};
template
constexpr auto GetAllNames()
{
// call it twice - once for length and once for the string
return FakeStringView(GetAllNamesImpl());
}
constexpr auto fakestringview = GetAllNames();
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79545997/is-there-a-standard-way-to-keep-the-result-of-a-constexpr-stdstring-function[/url]
Мобильная версия