Greetings,

I have a problem. I have an abstract class called Number and 3 derived classes called Integer,Double and Float. The Number class has an abstract virtual method, which the derived classes (obviously) must inherit. Now comes the part where im stuck. The method has to be declared using a template. Where do i have to declare this template? I tried in the number class, but in this case the method cannot be virtual it seems. Because of this, i also cannot declare it in the derived classes, because then it doesnt match the base-class method.

Any help would be much appriciated

>The method has to be declared using a template.
Why? What does this method do? Can you post your code?

Has to be declared using a template because that's what my instructions say (it's a part of my assignment).

Here's the code:

Class number

class Number
{
        public:
              virtual double getValue()const=0;
              virtual inline string toString()=0;
};

I'll only paste one of the 3 derived classes, because they are all the same except for the private variable which is of different type in every class (same type as the class name).

class Double : public Number
{
         private:
             double value;
         public:
               Double(double v):value(v){}
               ~Double(){}
               double getValue()const(return value;}
               inline string toString();
};

toString has to be declared using a template because it should be able to convert 3 different types of numbers. The template looks like this:

template <typename T>
inline string toString(const T& t)
{
  stringstream ss;
  ss<<t;
  return ss.str();
}

>toString has to be declared using a template because it
>should be able to convert 3 different types of numbers.
I don't see the problem. You have a global toString function that takes a template argument. You have a virtual toString member function that presumably calls the global function. The only thing you're missing is an overloaded << operator for the derived classes to be able to use the global toString function:

template <typename T>
inline string toString(const T& t)
{
  stringstream ss;
  ss<<t;
  return ss.str();
}

class Number
{
public:
  virtual double getValue()const=0;
  virtual string toString()=0;
};

class Double : public Number
{
private:
  double value;
public:
  Double(double v):value(v){}
  ~Double(){}
  double getValue()const {return value;}
  string toString() {return ::toString ( *this );}

  friend ostream& operator<< ( ostream& out, const Double& num )
  {
    return out<< num.value;
  }
};
This article has been dead for over six months. Start a new discussion instead.