// // cast.h // string-utils // // Created by Sam Jaffe on 2/13/21. // Copyright © 2021 Sam Jaffe. All rights reserved. // #pragma once #include #include #include #include #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 {}>> 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(tmp); return rval && tmp == static_cast(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 auto cast(std::string const &str) { using string_utils::cast; std::pair rval; rval.second = cast(str, rval.first); return rval; } }