Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "variant.h"
- #include <algorithm>
- #include <cstdlib>
- Variant::Variant(Type type)
- : type(type)
- { }
- Variant::Variant(Variant::Type type, const std::string& value)
- : type(type)
- {
- switch (type) {
- case Type::Int:
- ivalue = std::atoi(value.c_str());
- break;
- case Type::String:
- svalue = value;
- break;
- case Type::Nothing:
- break;
- }
- }
- Variant::Variant(const std::string& value)
- {
- if (std::find_if_not(begin(value), end(value), isdigit) != end(value)) {
- type = Type::String;
- svalue = value;
- } else {
- type = Type::Int;
- ivalue = std::atoi(value.c_str());
- }
- }
- Variant Variant::fromInt(int value)
- {
- Variant v;
- v.type = Type::Int;
- v.ivalue = value;
- return v;
- }
- Variant Variant::operator+(const Variant& x) const
- {
- if (type != x.type) {
- return Variant();
- }
- switch (type) {
- case Type::Int:
- return Variant::fromInt(ivalue + x.ivalue);
- case Type::String:
- return Variant(type, svalue + x.svalue);
- case Type::Nothing:
- return Variant();
- }
- return Variant();
- }
- Variant Variant::operator-(const Variant& x) const
- {
- if (type == x.type && type == Type::Int) {
- return Variant::fromInt(ivalue - x.ivalue);
- }
- return Variant();
- }
- Variant Variant::operator*(const Variant& x) const
- {
- if (type == Type::Int){
- if (x.type == Type::Int)
- return Variant::fromInt(ivalue * x.ivalue);
- if (x.type == Type::String) {
- Variant v(Type::String);
- for (int i = 0; i < ivalue; i++)
- v.svalue += x.svalue;
- return v;
- }
- }
- if (type == Type::String && x.type == Type::Int) {
- Variant v(Type::String);
- for (int i = 0; i < x.ivalue; i++)
- v.svalue += svalue;
- return v;
- }
- return Variant();
- }
- Variant Variant::operator/(const Variant& x) const
- {
- if (type == x.type && type == Type::Int) {
- return Variant::fromInt(ivalue / x.ivalue);
- }
- return Variant();
- }
- std::string Variant::toString() const
- {
- switch (type) {
- case Type::Nothing:
- // return std::string;
- return "!!! error !!!";
- case Type::Int:
- return std::to_string(ivalue);
- case Type::String:
- return svalue;
- default:
- return "!! unknown !!";
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement