Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.