0


I have a tempate class Operand<T> whose constructor is :

template <typename T>
Operand<T>::Operand(int precision, eOperandType type, std::string val)
   : precision(precision), type(type)
{
     std::istringstream inb(val);
     std::ostringstream err;
     T nb;

     inb >> nb;                                                          
     this->value = nb;
}

As the class is templated, it may be used with char, short int, int, float and double types, to create operands. My program must be able to execute basic instructions read from a file such as push in a stack, assert, add, mul, div, etc... with these operands.
I have to keep the values within strings from the parsing step to the execution step ; that's to say that when I'm done with parsing I begin to create asked operands of type T and I push them into a stack.
Everything is okay, I can execute almost every instruction perfectly except one thing : addition between Operand of type char.
Let's say I have the following content in a file :

push int8(1) // I create a Operand where T = char that contains 1 and I push it                      
into my operands stack push int8(13) // same there but my Operand contains 13 add // This instruction is linked to a operator+ overload, but broadly pops the 2
previous operands, creates a new Operand where T is the type of the 2 operands
(char in this case) which must stock the sum (13 + 1 = 14) dump // displays the content of the stack

Thus the output should be 14, but it displays 9 instead. While debugging I noticed that in my following operator+ overload, tnb1 (1) + tnb2 (13) = 98. Why is that?

template <typename T>
IOperand *              Operand<T>::operator+(const IOperand &rhs) const
{
  std::istringstream inb1(this->toString());
  std::istringstream inb2(rhs.toString());
  std::ostringstream res;
  T tnb1, tnb2;
  int l = 1;

  inb1 >> tnb1;
  inb2 >> tnb2;
  if ((tnb1 - tnb2) > std::numeric_limits<T>::max())
    {
      res << tnb1 << " + " << tnb2 << " make an overflow";
      throw CalcExcpt(l, res.str(), "operator+");
    }
  res << tnb1 + tnb2; // here, tnb1 + tnb2 = 98
  if (this->getType() > rhs.getType())
    return Calc::createOperand(this->getType(), res.str());
  return Calc::createOperand(rhs.getType(), res.str());
}
Amina
  • 404
  • 4
  • 14
  • 4
    It there some homework out there with this `Operand`? It's the third time I've seen this kind of question today. – juanchopanza Mar 02 '14 at 15:39
  • Related, possible duplicate: http://stackoverflow.com/questions/22127538/istringstream-to-int8-t-produce-unexpected-result – juanchopanza Mar 02 '14 at 15:41

0 Answers0