Files
toolkit/include/toolkit.h
2025-01-04 12:42:03 +08:00

38 lines
1013 B
C++

#ifndef TOOLKIT_H
#define TOOLKIT_H
#include <charconv>
#include <expected>
#include <type_traits>
#include <string_view>
//use for to_chars
constexpr size_t buffer_size = 32;
namespace toolkit{
//number to std::string;
template<typename T>
std::expected<std::string, std::string> itos(T value){
char buffer[buffer_size];
auto res = std::to_chars(buffer, buffer+buffer_size, value);
if(res.ec != std::errc()){
return std::unexpected(std::make_error_code(res.ec).message());
}
return std::string(buffer, res.ptr - buffer);
}
template<typename T = double>// requires std::is_same_v<T, std::string>
std::expected<T, std::string> stoi(const std::string& str){
T value;
auto res = std::from_chars(str.c_str(), str.c_str() + str.size(), value);
if(res.ec != std::errc()){
return std::unexpected(std::make_error_code(res.ec).message());
}
return value;
}
}
#endif