So i have this class called Numbers and I want to be able to take in doubles or integers.
I know i have to use templates but I'm confused can anyone guide me in the right direction.
suppose i have private member functions set to int how can I change those to doubles
how can I use a template to change those to doubles?

Recommended Answers

All 4 Replies

If you already have the class, you could do worse than simply change your existing code into template and see what happens.

If you class, for example, looks like this:

class Numbers
{
  private:
    int theValue;

  public:
   int getValue(){ return theValue;}
  void setValue(int input){theValue = input;}
};

you could just replace the int type with the template:

template <typename T>
class Numbers
{
  private:
    T theValue;

  public:
   T getValue(){ return theValue;}
  void setValue(T input){theValue = input;}
};

At the very simple level, all that happens is the compiler replaces the named template token (T in this case) with whatever type you try to use it with.

So you could then have code that creates a Numbers<int> and a Numbers<double>

template <typename T>
class Numbers
{
  private:
    T theValue;

  public:
   T getValue(){ return theValue;}
  void setValue(T input){theValue = input;}
};

#include <iostream>

  int main()
  {
    Numbers<int> x;
    x.setValue(4);
    std::cout << x.getValue() << std::endl; 
    Numbers<double> y;
    y.setValue(3.14159);
     std::cout << y.getValue() << std::endl;   
  }

Ok i understand that part, but in my main
i want it to be Numbers x
and through whatever the user inputs the number x can take in a double or integer value?

Get user input. Examine it. If it looks like an int, use a Numbers<int>. If it looks like a double, use a Numbers<double>. You will have to decide for yourself the logic of deciding how to gather the input and how to decide if it looks like an int or a double.

You could user something like:

struct Number
{
  union Value {int i; double d;} value;
  enum Type {integer, real, none} type;

  Number(): type{Type::none} {}

  void setvalue(int i)    {value.i = i; type=Type::integer;}
  void setvalue(double d) {value.d = d; type=Type::real;}
};

and later use it like:

 Number n;
  n.setvalue(3);

  if(n.type == Number::Type::integer) cout << "integer: " << n.i << "\n";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.