У меня есть структура/класс, которые форматируют числа. Я хочу настроить его параметры форматирования, как мне нравится. И это означает, что мне нужно «нужно» (не может быть, если есть еще один гораздо более умный способ сделать это?): < /P>
"Unsigned -> какое -то представление строки" преобразование; < /li>
Строковая конкатенация. Аргументы шаблона, как я вижу.#include
#include
#include // if there is an answer I guess
// Either these
constexpr ... constexpr_Concat(...) {...}
constexpr ... constexpr_To_String(...) {...}
// Or those
template
constexpr ... constexpr_Concat() {...}
template
constexpr ... constexpr_Concat() {...}
struct A
{
static constexpr unsigned
width = 10,
precision = 4;
// format strings below are what I want to be able to construct
static constexpr auto fmt_Str_Num = constexpr_Concat( // constexpr_Concat();
"{:",
constexpr_To_String(width), // constexpr_To_String()
'.',
constexpr_To_String(precision), // constexpr_To_String()
"f}"
);
// I want to be able to use one in others too
static constexpr auto fmt_Str_Vec2 = constexpr_Concat(
'(',
formatting_Num,
','
formatting_Num,
')'
);
};
int main()
{
float x = 1.23456789;
float y = 123456789;
// what I want in the end
std::print(A::fmt_Str_Num, x);
std::string str = std::format(A::fmt_Str_Vec2, x, y);
}
< /code>
Я пробовал свои собственные функции: < /p>
namespace compile_Time
{
template
consteval u8 len_Uint()
{
u8 res = 1;
auto temp = u;
while (temp/=10)
{
++res;
}
return res;
}
template
consteval fmt::string_view to_String()
{
std::array buffer{};
u8 pos = 0;
if (u == 0)
buffer[pos++] = '0';
else
{
auto temp = u;
while (temp > 0)
{
buffer[pos++] = '0' + temp%10;
temp /= 10;
}
for (u8 i = 0; i < pos / 2; ++i)
{
char temp = buffer;
buffer = buffer[pos - 1 - i];
buffer[pos - 1 - i] = temp;
}
}
return fmt::string_view(buffer.data(), pos);
}
}
Я пробовал прочитать "fmt/compile.h" и сыграл с некоторыми вещами.E0028: expression must have a constant value
invalid use of address of interpreter storage
Подробнее здесь: https://stackoverflow.com/questions/797 ... mpile-time
Есть ли способ «настроить» форматирование во время компиляции? ⇐ C++
Программы на C++. Форум разработчиков
-
Anonymous
1756453561
Anonymous
У меня есть структура/класс, которые форматируют числа. Я хочу настроить его параметры форматирования, как мне нравится. И это означает, что мне нужно «нужно» (не может быть, если есть еще один гораздо более умный способ сделать это?): < /P>
"Unsigned -> какое -то представление строки" преобразование; < /li>
Строковая конкатенация. Аргументы шаблона, как я вижу.#include
#include
#include // if there is an answer I guess
// Either these
constexpr ... constexpr_Concat(...) {...}
constexpr ... constexpr_To_String(...) {...}
// Or those
template
constexpr ... constexpr_Concat() {...}
template
constexpr ... constexpr_Concat() {...}
struct A
{
static constexpr unsigned
width = 10,
precision = 4;
// format strings below are what I want to be able to construct
static constexpr auto fmt_Str_Num = constexpr_Concat( // constexpr_Concat();
"{:",
constexpr_To_String(width), // constexpr_To_String()
'.',
constexpr_To_String(precision), // constexpr_To_String()
"f}"
);
// I want to be able to use one in others too
static constexpr auto fmt_Str_Vec2 = constexpr_Concat(
'(',
formatting_Num,
','
formatting_Num,
')'
);
};
int main()
{
float x = 1.23456789;
float y = 123456789;
// what I want in the end
std::print(A::fmt_Str_Num, x);
std::string str = std::format(A::fmt_Str_Vec2, x, y);
}
< /code>
Я пробовал свои собственные функции: < /p>
namespace compile_Time
{
template
consteval u8 len_Uint()
{
u8 res = 1;
auto temp = u;
while (temp/=10)
{
++res;
}
return res;
}
template
consteval fmt::string_view to_String()
{
std::array buffer{};
u8 pos = 0;
if (u == 0)
buffer[pos++] = '0';
else
{
auto temp = u;
while (temp > 0)
{
buffer[pos++] = '0' + temp%10;
temp /= 10;
}
for (u8 i = 0; i < pos / 2; ++i)
{
char temp = buffer[i];
buffer[i] = buffer[pos - 1 - i];
buffer[pos - 1 - i] = temp;
}
}
return fmt::string_view(buffer.data(), pos);
}
}
Я пробовал прочитать "fmt/compile.h" и сыграл с некоторыми вещами.E0028: expression must have a constant value
invalid use of address of interpreter storage
Подробнее здесь: [url]https://stackoverflow.com/questions/79749962/is-there-a-way-to-configure-formatting-at-compile-time[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия