I'm writing a scripting language and I'm trying to implement a dynamic number type in C++. Right now, I'm only interested in getting long double
s and long long
s working right. I was able to get this contraption to work. I would like to know if there's an easier, more organized idea than mine.
I don't want the class to have any arithmetic operators, I just want it to be a generic numeric container. Everything else, I want to take advantage of all arithmetic overloads that C++ already has (example: myNum1.data + myNum2.data
) - even though they can be of different numeric types, C++ will work its casting magic.
#include <algorithm>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
using std::cout;
using std::endl;
template <typename t>
class number {
public:
t data {};
number(t const p_data)
: data {p_data}
{}
std::string to_string() const {
std::ostringstream output;
output.precision(std::numeric_limits<t>::max_digits10);
output << std::uppercase << data;
return output.str();
}
};
template <typename t>
number<t> make_number(t const p_input) {
return number<t>(p_input);
}
enum class number_t {
integer_t,
float_t,
error_t
};
number_t validate(std::string const & p_input) {
if (all_of(cbegin(p_input), cend(p_input), isdigit)) {
return number_t::integer_t;
} else {
std::istringstream input {p_input};
double long output;
input >> output >> std::ws;
if (!input.fail() && input.eof()) {
return number_t::float_t;
} else {
return number_t::error_t;
}
}
return number_t::error_t;
}
int main() {
std::string test {"9223372036854775809"};
auto result = make_number(
validate(test) == number_t::integer_t
? (test > "9223372036854775807" ? 9223372036854775807 : stoll(test))
: validate(test) == number_t::float_t
? stold(test)
: 0);
cout << result.data << endl;
std::string test_string {result.to_string()};
cout << test_string << endl;
return 0;
}
auto result = make_number
has? Do you thinkresult
could have a different type based on the value in the stringtest
? I suspect your problem is "auto
does not work that way" \$\endgroup\$expected<T,E>
type, or exceptions). \$\endgroup\$