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

do you want the class to be templated or just the functions of the class?

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

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;
}
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.