| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- //
- // cast.h
- // string-utils
- //
- // Created by Sam Jaffe on 2/13/21.
- // Copyright © 2021 Sam Jaffe. All rights reserved.
- //
- #pragma once
- #include <cstdlib>
- #include <string>
- #include <type_traits>
- #include <utility>
- #include "any_of.h"
- #define cast_number_impl(type, func, ...) \
- bool cast(std::string const &str, type &to) { \
- char *rval; \
- to = func(str.c_str(), &rval, ##__VA_ARGS__); \
- return rval == str.c_str() + str.length(); \
- }
- namespace string_utils {
- template <typename T, typename = std::enable_if_t<std::is_constructible<T, std::string const &>{}>>
- bool cast(std::string const &str, std::string &to) { to = T(str); return true; }
- cast_number_impl(long, std::strtol, 10)
- cast_number_impl(long long, std::strtoll, 10)
- cast_number_impl(float, std::strtof)
- cast_number_impl(double, std::strtod)
- cast_number_impl(long double, std::strtold)
- bool cast(std::string const &str, int &to) {
- long tmp;
- bool rval = cast(str, tmp);
- to = static_cast<int>(tmp);
- return rval && tmp == static_cast<long>(to);
- }
- bool cast(std::string const &str, bool &to) {
- if (any_of(str, "true", "TRUE", "YES", "1")) {
- to = true;
- return true;
- } else if (any_of(str, "false", "FALSE", "NO", "0")) {
- to = false;
- return true;
- }
- return false;
- }
- template <typename T>
- auto cast(std::string const &str) {
- using string_utils::cast;
- std::pair<T, bool> rval;
- rval.second = cast(str, rval.first);
- return rval;
- }
- }
|