Last active
May 6, 2019 08:55
-
-
Save kateolenya/f868e2cf7154bf80d16521b0f5fb6799 to your computer and use it in GitHub Desktop.
Example of specialized template class in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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