Generics in C++

Generics in Object

template <class T>
class Myclass{
    T a, b;
 public:
    Myclass(T first, T second)
  {a=first; b=second;}
    T getmax ();
};
template <class T>
T Myclass::getmax ()
{
  T retval;
  retval = a>b? a : b;
  return retval;
}

int main () {
  mypair  myobject (100, 75);
  cout << myobject.getmax();
  return 0;
}

Generics in Function

template <class SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}

template <class T >
bool are_equal (T a, T b)
{
 return (a==b);
}

template 
bool are_equal (T a, U b)
{
 return (a==b);
}

int main ()
{
  if (are_equal(10,10.0))
    cout << "x and y are equal\n";
  else
    cout << "x and y are not equal\n";
  return 0;
}


Advertisements
This entry was posted in C\C++ and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s