use to_string to replace itos

This commit is contained in:
Jie 2025-01-06 14:11:58 +08:00
parent bac6287497
commit a2d35ba747

View File

@ -5,32 +5,44 @@
#include <expected> #include <expected>
#include <type_traits> #include <type_traits>
#include <string_view> #include <string_view>
#include <string>
#include <ios>
//use for to_chars //use for to_chars
constexpr size_t buffer_size = 32; constexpr size_t buffer_size = 32;
template <typename T>
concept _num_type = requires {
std::is_same_v<T, int> ||
std::is_same_v<T, float> ||
std::is_same_v<T, long> ||
std::is_same_v<T, double>;
};
namespace toolkit{ namespace toolkit{
//number to std::string;
template<typename T> template<typename T>
std::expected<std::string, std::string> itos(T value){ std::expected<std::string, std::string> to_string(T value){
char buffer[buffer_size]; if constexpr (std::is_same_v<T, int> || std::is_same_v<T, float> || std::is_same_v<T, double>){
auto res = std::to_chars(buffer, buffer+buffer_size, value); char buffer[buffer_size];
if(res.ec != std::errc()){ auto res = std::to_chars(buffer, buffer + buffer_size, value);
return std::unexpected(std::make_error_code(res.ec).message()); if (res.ec != std::errc()) {
return std::unexpected(std::make_error_code(res.ec).message());
}
return std::string(buffer, res.ptr - buffer);
} else if constexpr (std::is_same_v<typename std::remove_const<T>::type,
char *>) {
return std::to_string(value);
} }
return std::string(buffer, res.ptr - buffer);
} }
template<typename T = double>// requires std::is_same_v<T, std::string> template<typename T = double>// requires std::is_same_v<T, std::string>
std::expected<T, std::string> stoi(const std::string& str){ std::expected<T, std::string> stoi(const std::string& str){
T value; T value;
auto res = std::from_chars(str.c_str(), str.c_str() + str.size(), value); auto res = std::from_chars(str.c_str(), str.c_str() + str.size(), value);
if(res.ec != std::errc()){ if(res.ec != std::errc()){
return std::unexpected(std::make_error_code(res.ec).message()); return std::unexpected(std::make_error_code(res.ec).message());
} }
return value; return value;
} }
} }