While generic templates work across all types, occasionally a specific type requires specialized behavior (for instance, treating bool as bit flags or optimizing const char* pointer string comparisons).
#include <iostream>
#include <cstring>
// Generic template
template <typename T>
bool areEqual(T a, T b) {
return a == b;
}
// Full Specialization for C-strings (const char*)
template <>
bool areEqual<const char*>(const char* a, const char* b) {
return std::strcmp(a, b) == 0; // Compares string contents, NOT pointer addresses!
}
int main() {
std::cout << std::boolalpha;
std::cout << "Numbers: " << areEqual(10, 10) << "\n"; // true
std::cout << "Strings: " << areEqual("Veewom", "Veewom") << "\n"; // true (via specialization)
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
General template function and class blueprints.
Accepting variable numbers of template arguments.
Modern type constraints replacing template specialization.