0

Hi Everybody

I am trying to create a template class here is the code I trying to just add and multiply 2 number. But I am not able to do so using template class.

 class calc
{
  public:
template <class T>
    T multiply(T x, T y);
    T add(T x, T y);
};
template <class T> T calc<T>::multiply(T x,T y)
{
  return x*y;
}
template <class T> T calc<T>::add(T x, T y)
{
  return x+y;
}

int main ()
{
  calc <T> c1;
  int i=5, j=6, k;
  long x=40, y=20, z;
  k=c1.multiply<int>(i,j);
  z=c1.add<long>(x,y);
  cout << k << endl;
  cout << z << endl;
  return 0;
}

Thank you in advance for any guidance

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by mike_2000_17
0

Thank you NathanOliver for considering my issue -
I want class to be templated.

0

The simple fix is to take the template <class T> and put it just before the class template declaration. Also, you need to specify the type (for T) when creating an object, but you don't need it when calling its functions. As so:

template <class T>
class calc
{
  public:
    T multiply(T x, T y);
    T add(T x, T y);
};
template <class T> T calc<T>::multiply(T x,T y)
{
  return x*y;
}
template <class T> T calc<T>::add(T x, T y)
{
  return x+y;
}

int main ()
{
  calc <int> c1;   // specify T = int
  int i = 5, j = 6, k;
  long x = 40, y = 20, z;
  k = c1.multiply(i,j);
  z = c1.add(x,y);
  cout << k << endl;
  cout << z << endl;
  return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.