Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created October 18, 2015 15:31
Show Gist options
  • Save krysseltillada/c631256a690cf3a8b0f1 to your computer and use it in GitHub Desktop.
Save krysseltillada/c631256a690cf3a8b0f1 to your computer and use it in GitHub Desktop.
template specialization
#include <iostream> /// std::cout
#include <cstdlib> /// #EXIT_SUCCESS --> macro definition
template <typename T>
T sum (const T &t1, const T &t2) {
return t1 + t2;
}
///******** template specializations of <T> sum ******************///
template <> /// template specialization of sum that takes a const int &, const int &
int sum (const int &s1, const int &s2) {
return s1 + s2;
}
template <> /// template specialization of sum that takes a const double &, const double &
double sum (const double &s1, const double &s2) {
return s1 + s2;
}
template <> /// template specialization of sum that takes a int * const &, int * const &
int *sum (int * const &sptr1, int * const &sptr2) {
int *sp = new int (0);
*sp = *sptr1 + *sptr2;
return sp;
}
template <> /// template specialization of sum that takes a double * const &, double * const &
double *sum (double * const &sptr1, double * const &sptr2) {
double *sp = new double (0.0);
*sp = *sptr1 + *sptr2;
return sp;
}
int main ()
{
int n1 = 22, n2 = 24;
int *ptr1 = &n1, *ptr2 = &n2;
int *r = sum (ptr1, ptr2);
std::cout << *r << std::endl;
delete r; /// free the allocated mem from the template func
return EXIT_SUCCESS; /// system independent return call
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment