-2

My project is about making a VM that does basic math over customs types so i have:

typedef char    int8;
typedef short   int16;
typedef int     int32;

I have a Basic Factory which creates IOperands when i do:

Factory         f;

f.createOperand(INT8, "1");
f.createOperand(INT16, "20");
f.createOperand(INT32, "-1234567");

My problem is that i need to check if the string passed as parameters does OverFlow or UnderFlow the type that i want to create a variable with...

something like :

if (value < CHAR_MIN || value > CHAR_MAX)
{
   // do something... 
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Thomas Billot
  • 163
  • 1
  • 10
  • 3
    It's not clear what you're asking for help with. – Tyler Jul 15 '16 at 14:17
  • 3
    Why the typedefs? Why not just use the standard `int8_t`, `int16_t` & `int32_t`? Besides, depending on platform, your typedefs are *wrong* - for example, `int` is not guaranteed to be 32bit (same for `short` and 16bit). – Jesper Juhl Jul 15 '16 at 14:18
  • Are you processing a language, like the Java Virtual Machine does? – Thomas Matthews Jul 15 '16 at 15:29

1 Answers1

0

Looks like you could use an Abstraction class and several type classes.

The Abstract, Parent or Root class would contain generic methods that all children have to implement.

For example:

class Base_Type
{
  public:  
    virtual bool value_is_in_range(const std::string& value_as_text) const = 0;
};  

Each child class would specialize the abstract method:

class Uint8_Type
{
  public:
    bool  value_is_in_range(const std::string& value_as_text) const
    {
       std::istringstream value_stream(text);
       unsigned int value;
       value_stream >> value;
       if (value > CHAR_MAX)
       {
          return false;
       }
       return true;
    }
  };

Two concepts here: 1) a common, universal data type for passing values; 2) If converting the string to number for range checking, the number must be of a larger type.

I chose a std::string and using text as a universal data type. Most PODs can be represented as text.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154