example5_function_template_specialization.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

// Generic template
template<typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

// Specialized template for const char*
template<>
const char* getMax(const char* a, const char* b) {
    return (std::strcmp(a, b) > 0) ? a : b;
}

int main() {
    std::cout << "Max of 10 and 20: " << getMax(10, 20) << std::endl;
    std::cout << "Max of 'Apple' and 'Banana': " << getMax("Apple", "Banana") << std::endl;

    return 0;
}
Back to templates