Skip to content

Instantly share code, notes, and snippets.

@kateolenya
Last active May 6, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kateolenya/f868e2cf7154bf80d16521b0f5fb6799 to your computer and use it in GitHub Desktop.
Save kateolenya/f868e2cf7154bf80d16521b0f5fb6799 to your computer and use it in GitHub Desktop.
Example of specialized template class in C++
#include <iostream>
using namespace std;
template <class T>
class Two_values {
T a;
T b;
public:
Two_values (T first_arg, T second_arg) {
a = first_arg;
b = second_arg;
}
void custom_add () {
cout << "General result = " << (a + b) << endl;
}
};
template <> // Note: no 'T' here
class Two_values <char> { // <char> specifier instead
char a;
char b;
public:
Two_values (char first_arg, char second_arg) {
a = first_arg;
b = second_arg;
}
void custom_add () {
cout << "Char result = " << a << b << endl;
}
};
int main () {
Two_values <int> Two_int_values (1, 2);
Two_values <char> Two_char_values ('a', 'b');
Two_int_values.custom_add();
Two_char_values.custom_add();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment